You don't show the type of newGame
but I would guess that it is of type std::string
and you enter a title with two words: the stream reads the first word and stops reading. The next thing you do is read an int
which fails and leaves the value of option
unchanged. From then on the stream won't do anything and just keeps reading.
The key error is not checking that the read attempt was successful before using the result: you always need to verify that your input was successful after reading and before using the result. When an input operation fails the stream goes into failure mode, i.e., std::ios_base::failbit
gets set, and it converts to false
instead of true
(well, actually it converts to a null pointer vs. a non-null pointer but that's a detail irrelevant to this discussion). Once in failure state the stream won't do anything until the stream state is clear()
ed. You you probably also need to ignore()
the offending characters.
That is, you certainly should use something like
if (std::cin >> option) {
// do something with the option
}
else {
std::cout << "expected an integer: ignoring the line\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
To read the title you should probably read an entire line. Since the formatted input for the option
will leave the newline character in the stream, you will first need to skip that character, though. That is, the input for the new title would look something like this:
if (std::getline(std::cin >> std::ws, newGame)) {
// ...
}
The std::ws
manipulator skips all leading whitespace. That is probably OK for your needs. If the string being read can have leading whitespace characters something different will be needed.