Invalid input in a C ++ stream

Consider the following code that takes integer input and then prints the state of the cin stream:

#include <iostream>  
using namespace std;

int main()
{
    int number;
    cout<<"Enter a number \n";
    cin>>number;
    cout<<cin.rdstate()<<endl;
    return 0;
}

If the entered number is "zzzz", then rdstate will return 4.
If the entered number is "10zzzz", then rdstate will return 0, the number will be 10, and the input stream will have "zzzz" in it.

My question is:
1. Why is the input "10zzzz" not considered an invalid input (at least one of the failure bits must be set.)
2. What is an elegant solution to detect and handle this situation.

Thank!!!

+3
source share
1 answer

First of all, I would like to ask what are you trying to do:

cout<<cin.rdstate()<<endl;

rdstate() http://www.cplusplus.com/reference/iostream/ios/rdstate/

: , , , - , .

:

int main() {

 string input = "";

 // How to get a string/sentence with spaces
 cout << "Please enter a valid sentence (with spaces):\n>";
 getline(cin, input);
 cout << "You entered: " << input << endl << endl;

 // How to get a number.
 int myNumber = 0;

 while (true) {
   cout << "Please enter a valid number: ";
   getline(cin, input);

   // This code converts from string to number safely.
   stringstream myStream(input);
   if (myStream >> myNumber)
     break;
   cout << "Invalid number, please try again" << endl;
 }
 cout << "You entered: " << myNumber << endl << endl;

 // How to get a single char.
 char myChar  = {0};

 while (true) {
   cout << "Please enter 1 char: ";
   getline(cin, input);

   if (input.length() == 1) {
     myChar = input[0];
     break;
   }

   cout << "Invalid character, please try again" << endl;
 }
 cout << "You entered: " << myChar << endl << endl;

 cout << "All done. And without using the >> operator" << endl;

 return 0;
}
+1

All Articles