problem with a Hello World application



  • #include <string>
    #include <iostream>
    
    using namespace std;
    
    int main() {
      string name1;
      char age1;
    
      do {
        cout << "What is your name\n";
        getline (cin, name1 );
    
        cout << "What is your age?\n";
        cin >> age1;
        cin.get();
    
        if (age1 >= 18)
          cout << " Hi there " << name1 << ", you are allowed to enter.";
        else
          cout << "Hi there " << name1 << ", Darklink sends you his regards.";
      }
      while (!isdigit(age1));
    
      cout << "\nMade by Mithos Y.\n";
    
      cin.get();
      return 0;
    }
    

    this was originally posted by Rascar-Capac on a wrong board...
    His problem was that when you enter a letter when de program asks for your age, the program quits...
    for some reason this code (wich is edited by on of you guys) doesn't work well 😉
    can someone please help with this one?
    greetings,
    DL 🙄



  • Darklink schrieb:

    if (age1 >= 18)
    

    you compare here ascii values

    try this without the do/while loop

    int age1 = 0;
    // ...
    cin >> age1; // if cin fails the value from age is 0
    // ...
    


  • and after this, you should also check and reset the state of cin to detect any errors inside the user input:

    if(!cin) //an error occured
    {
      cerr<<"wrong input\n";
      cin.clear(); //reset error flags - otherwise cin would ignore any future input requests
    }
    

Anmelden zum Antworten