Reputation: 23
I ran into a problem while trying to validate my user input. Here's my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string choice;
cout << "Please type something: ";
cin >> choice;
cin.ignore();
while (choice != "1" && choice != "2" && choice != "3" && choice != "4" && choice != "5")
{
cout << "Incorrect choice! Please input a valid number: >_";
cin >> choice;
cin.ignore();
}
return 0;
}
When I input "wronginput", that input fell in the while loop and displayed
Incorrect choice! Please input a valid number: >_
Which is good. However, when I try "wrong input", I get a "weird" version of it:
Incorrect choice! Please input a valid number: >_ Incorrect choice! Please input a valid number: >_
My guess is that the space in between is the culprit. Is there any way for me to fix this? Thank you.
Upvotes: 2
Views: 103
Reputation: 206567
When you enter "wrong input" for input, the line
cin >> choice;
reads and stores "wrong" in choice
.
The line
cin.ignore();
ignores only one character. Hence, you stull have "input" and the subsequent newline character in the stream. Next time you read into choice
, you get "input" in choice
.
That explains the behavior of your program.
In order to fix it, make sure to ignore the rest of the line instead of just one character. Use
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Add
#include <limits>
to be able to use std::numeric_limits
.
Upvotes: 1
Reputation: 13424
That's because std::cin >> choice
is a formatted input that will read everything to the next whitespace.
When you type in "wronginput", it reads it all, but if you type in "wrong input", only the "wrong" part will be read. Your while
loop will fire, perform std::cin >> choice
inside its body once again and that will read "input".
This behaviour causes your program to output the message twice in a row.
How to fix it? Instead of reading a single token, up to the next whitespace, consider reading an entire line.
How to achieve that? Simply instead of using
std::cin >> choice;
use a std::getline
function:
std::getline(std::cin, choice);
both outside and inside your while
loop.
Upvotes: 0