validation - C++ how to restart the loop if user just presses enter or if the input is invalid? -


i'll start saying have worked on 3 days , second semester programming. know question easy most, have little experience.

the code have written works intended except invalid/blank entry validation. have found , tried breaks other parts of code or doesn't work @ all.

here instructions given in homework part having issues with: "any invalid input menu redisplay menu. option 1 prompt username. empty name ignored."

here code. appreciated.

#include <iostream> #include <vector> #include <string>    using namespace std; vector<string> usernames; void listmenu(); void addname(); void listnames(); void removename();  int main() {      char entry;     bool exit = false;      while (exit == false)     {          cout << "choose following menu: \n";         listmenu();         cin >> entry;          if (entry == '\n')         {             listnames();         }          if (entry == '1')         {             addname();         }         else if (entry == '2')         {             listnames();         }         else if (entry == '3')         {             removename();         }         else if (entry == 'x' || entry == 'x')         {             exit = true;         }        }         usernames.clear();     return 0;  }  void listmenu() {     string menu[4] = { "1. add username","2. list usernames","3. delete username","x. exit" };          (int = 0; < 4; i++) {             cout << menu[i] << endl;         }  }  void addname() {     string name;     cout << "enter username: " << endl;     cin >> name;         usernames.push_back(name);  }  void listnames() {     int n = 1;     cout << "**************\n";     (auto& x : usernames)     {         cout << n <<". "<< x <<endl;         n++;     }     cout << "**************\n"; }  void removename() {     int x;     cout << "which username remove?\n";     listnames;     cin >> x;      usernames.erase(usernames.begin()+x); } 

you can test input , clear if it's invalid. using cin.fail, cin.clear , cin.ignore.

#include<iostream>   using namespace std;    bool cond;    int main() {       int n;        {           cout << "enter integer number:";           cin >> n;            cond = cin.fail();            cin.clear();           cin.ignore(int_max, '\n');       } while(cond);        return 0;   } 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -