validation - C++: How can I allow user to retry if they accidentally enter more than one character in char variable? -


question: in c++, ow make program throw out error when user enters multiple characters input requesting single character? i'd have program re-prompt single character, keeps going , entering multiple characters on later lines.

this simple program wrote test out character inputs , properties me assignment. wanted see how react multi-character inputs.

//include statements #include <iostream> #include <string>  using namespace std;  //main statement  int main () {      //name variables     int numchar;     char letterentry;     string finalword = "";      //begin entry      cout << "this program let enter characters , combine them string." << endl;     cout << "first tell how many characters want enter." << endl;     cin >> numchar;      //convert characters string , add string variable     int counter = 0;     while (counter<numchar)     {         cout << "enter character!" << endl;         cin >> letterentry;          finalword = finalword + string(1, letterentry);         counter++;     }     //display final word     cout << "your word " << finalword << endl;      return(0); } 

this output demonstrates issue.

this program let enter characters , combine them string. first tell how many characters want enter. 3 enter character! dogs enter character! enter character! word dog 

i want program not save if user types in more 1 character. want print error message says "you entered more 1 character, please retry," , lets them try again. there way type char?

thanks!


Comments