Search code examples
c++loopsif-statementciniomanip

C++ - How do you loop back after user input?


In my previous question, I got this answer to work so that if the user inputs more than 5 characters in the nation name, it will output an error.

#include <iostream>
#include <iomanip>

int main()
{
    using namespace std;

    const int maxchar = 5;
    string nationname;

    cout << "What is the name of your nation?" << endl;

    cin >> nationname;

    if (nationname.size() > maxchar)
    {
       cout << "The input is too long." << endl;
       return 1;
    }
}

I want it so that it will loop back to the "cout << what is the name..." after it outputs the error.

Thanks!

Someone answered on my previous question how in the comments but I didn't get it to work/I don't know how or where to put it in my code.


Solution

  • while(1){
        cin >> nationname;
        if (nationname.size() <= maxchar)
            break;
        else{
           cout << "The input is too long." << endl;
        }
    }