I have been trying to figure out how to get a simple program to work, however I am getting hung up on taking user input from the console. I am able to take in a list of integers (eg. 3 5 3 2 1 8 9) into a vector, however I need to also take in one more user input for the number I need to check if it is inside the vector.
When I run the code, it always skips over the second cin and does not allow any more console input, finishing the program. My best understanding is that since cin does not take white space into account, using a second line will not work. However, I do not understand after breaking the while loop it will skip over my next cin statement. Another way I can think of getting it to work is possibly using getline for the first line of input, however I am not sure of how to get that to work especially when converting back to an integer.
Sample Input for line 1 on console: 2 7 6 7 8 5 67 54 3 (these will go into a vector)
Sample Input for line 2 on console: 54 (this will just go into another variable num)
int i;
vector<int> v;
int num;
cout << "When finished entering numbers type any letter and hit enter" << endl << "Enter list of numbers: ";
while (cin >> i)
{
v.push_back(i);
}
cout << endl << "Enter number to be found: ";
cin >> num;
cout << endl;
CodePudding user response:
Your while
loop is reading integers from the input stream std::cin
, so if you enter a letter std::cin
goes into an error state and will remain there until you explicitly clear the error state.
To clear the error state, call cin.clear()
. But invalid input remains in the stream. To ignore all the remaining characters in the stream, call cin.ignore()
like this:
std::cin::ignore(std::numeric_limits<std::streamsize>::max(), '\n');
So please add following two lines after the while loop, then your program should work as expected.
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Output:
When finished entering numbers type any letter and hit enter
Enter list of numbers: 1
2
3
4
abcde
Enter number to be found: 3
CodePudding user response:
Call cin.clear()
after the loop. This should clear all error flags.
In your case you might want to skip the next newline aswell with cin.ignore(10000, '\n')
.
CodePudding user response:
Since you are expecting multiple kinds of input from the user--int
and not int
--you can also read into a std::string
in the loop condition and then explicitly test if the read text can be converted to an int
.
std::string input;
std::vector<int> v;
while(std::cin >> input)
{
try
{
v.push_back(std::stoi(input));
}
catch(const std::invalid_argument&) // input is not an int
{
break;
}
}
This way, std::cin
is always in a good state. When you get to the second std::cin >> num
, there's no error in std::cin
and there's no extra data in the stream.