C++ user input restriction with proper retry without “goto”

前端 未结 5 691
Happy的楠姐
Happy的楠姐 2021-01-15 14:01

I have the following code:

qstn:
  cout << \"Input customer\'s lastname: \";
  getline(cin, lname);

  if (lname.find_first_not_of(\"abcdefghijklmnopqr         


        
5条回答
  •  终归单人心
    2021-01-15 14:18

    A While loop looks like your best bet. You can redo the loop with the continue keyword.

    int incorrect = 0;
    while(!incorrect) {
    cout<<"Input customer's lastname: ";
            getline(cin,lname);
    
            if(lname.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ")!=string::npos)
                {
                cout<<"You can only input alpha here!\n";
                cin.clear();
                continue;
                }
            else if(lname.empty())
            {
                cout<<"Please enter your firstname!\n";
                cin.clear();
                continue;
            }
            int lnamel=lname.length();
            int strl=str.length();
            int is=0;
            for(int i=1; i

提交回复
热议问题