I wanted to try making a pretty basic text game, to apply what I've learned so far. But I'm stuck here. In a while loop, when I use an if statement and insert continue at the end, it does go back to the beginning of the loop (like it should).
But when it does, it completely ignores the line "std::cin >> input;" and goes directly to if and then again to the beginning and so on. And the output is infinite lines of the two strings you see in the code. What should I do?
(I want it to go back to the first line of loop if input is not an integer.)
1 2 3 4 5 6 7 8 9 10 11 12
while(true) {
std::cout << "What will you do? > " ;
int input;
std::cin >> input;
if (std::cin.fail()) {
std::cout << "You don't seem to have any other option. " << std::endl;
continue;
}
Once std::cin fails, it goes into a bad state and won't take any more input.
This is solved by calling std::cin.clear();
Next, std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); is also needed to ignore the rest of the bad input, so that it doesn't keep failing, then clearing.
Also, it is suggested to just useif (!std::cin) as opposed to std::cin.fail(). I believe the reasoning for this is that if input reaches end of file (such as when the program input is being redirected from a file), it doesn't count as a failure. Just doing !std::cin captures all possible input problems. Nevermind, as Chervil pointed out, the boolean not and .fail() are equivalent.
// Example program
#include <iostream>
#include <string>
#include <limits>
int main()
{
while(true) {
std::cout << "What will you do? > " ;
int input;
std::cin >> input;
if (!std::cin) {
std::cout << "You don't seem to have any other option. " << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
continue;
}
// I assume more code is here
}
}
That was a very helpful reply in many ways Ganado. I got the logic of it and it works now. Though std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); looks confusing for now, I'm gonna learn what exactly is that. Anyways, thank you for the help!
According to the reference pages on this site, using the ! operator on a stream is equivalent to calling the fail() member. That is, for practical purposes there is no difference.
it completely ignores the line "std::cin >> input;" and goes directly to if and then again to the beginning and so on.
It's not clear from your prompt at line 2 whether you're expecting alpha or numeric input. Your cin statement at line 5 is expecting only numeric input (an int). If the user enters alpha input, the cin will fail and the fail bit will be set on the stream as has been pointed out. If you're expecting alpha input, you should be inputting to a std::string.