Beginner



  • Hi there, i'm a beginner when it comes to C++... I use Bloodshed C++ to make beginners console applications, these tasks and classes are for school by the way... Yesterday i made a somewhat different Hello World app. This is the source-code:

    # include <iostream>
    using namespace std;
    
    int main()
    {
    string name1;
    int age1;
    
    cout << "What is your name" << endl;
    getline (cin, name1 );
    
    cout << "What is your age?" << endl;
    cin >>age1;
    cin.get();
    
    if (age1 >= 18)
    {
    cout << " Hi there " << name1 << ", you are allowed to enter";
    }
    
    else 
    {
        cout << "Hi there " <<name1 << ", Rascar Capac sens you his regards";
    }
    cout << "" << endl;
    cout << " Made by Rascar C." << endl;
    
    cin.get();
    return 0;
    }
    

    Now i have a question wich i hope you will help me with... When i enter a letter when there is asked for my age, the program quits on its own. How do i make sure that when someone enters a letter instead of a number, there will be a message the input is not correct, so the program will take them back to the name/ age option. I really hope you can help me with this..

    Greetings, Rascar... :)[code]



  • Hi,

    wrong board, post to ANSI C or C++ next time. Moreover you could use the cpp tags to enable syntax highlighting.

    To solve your problem, I used a char instead of an int and a do-while loop to check whether the entered age is a digit:

    #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 << ", Rascar Capac sends you his regards.";
      }
      while (!isdigit(age1));
    
      cout << "\nMade by Rascar C.\n";
    
      cin.get();
      return 0;
    }
    

    Bye

    GPC



  • Thank you very much 🙂 😃


Anmelden zum Antworten