This may at first seem like an odd question, but when a cin request is made, if it receives the wrong type it still continues but the status of cin changes.
How do I loop until cin is OK, e.g. when I ask for a number it "accepts" a string if no extra code is given e.g. a loop?
Finally when I use cin multiple times in a row it does the first cin as expected but then skips the rest; how do I fix this? If you need more information just ask in a comment.
// Example
cout << "Enter a number: ";
cin >> num; // A string is given
cout << "Enter another number: ";
cin >> num2;
In the example above the string would be kinda accepted and the second cin would most likely skip for some reason. I had a while ago find the answer to this question but I lost the snippet of the loop I used so :/
example:
int value;
while(!(cin >> value))
{
cin.clear();
cin.ignore(); // eat one character
}
while(!(cin >> value))
{
cin.clear();
cin.ignore(10000,'\n'); // eat the rest of the line
}
Related
I have gone through many existing answers here StackOverflow, but I am still stuck.
code:
int c;
cin >> c;
if(cin.fail()) {
cout << "Wrong Input";
cin.clear();
cin.ignore(INT_MAX, '\n');
}
else
{
cout << c*2;
}
If I enter wring input e.g s instead of an integer, it outputs Wrong Input. However, if I enter an integer, and then I enter a string, it ignores the string and keep outputting the previous integer result, hence it does not clears the cin buffer, and the old value of c keeps on executing.
Can anyone please suggest the best way other than cin.ignore() as it does not seem to work.
and yeah for me, the max() in cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); gives error. So this does not work either.
the max() function needs to be defined in the beginning of the file. cin.ignore() works very well to clear the buffer, however you need the numeric limits function max(), which in my case was giving error.
Solution:
#ifdef max
#define max
#endif
add these lines on the top, and a function such as following will work fine.
int id;
bool b;
do {
cout << "Enter id: ";
cin >> id;
b = cin.fail();
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
} while ( b == true);
P.S: Thanks #Nathan
Why do I get an infinite loop when I press a letter? How do I prevent my code from going into an infinite loop when error checking?
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter a number in the range 1-100: ";
cin >> number;
while (number > 1 || number < 100)
{
cout << "ERROR: Enter a value in the range 1-100: ";
cin >> number;
}
return 0;
}
Because std::cin is type safe, it knows that a letter is not a valid input for "int number". It raises an error flag in std::cin and any subsequent operation will fail and return immediately.
You'll need to check the error state and clear any error flag(s) before you can proceed.
See existing post Why do I get an infinite loop if I enter a letter rather than a number?
Thanks a lot y'all. I ended up going with this one.
while (!(cin >> number))
{
cout << "ERROR: Enter a value in the range 1-100: ";
//to clear input stream
cin.clear();
//to discard previous input
cin.ignore(1200, '\n');
cin >> number;
}
I am stumped about this. So I wrote some code to try to explain it. I was wondering why I am able to store numbers or characters even though I have not prompted input with cin or getline? The only thing I can think of right now with my limited knowledge is "while (!(cin >> num1))" but then again, why would a while loop execute the condition?
#include <iostream>
#include <limits>
using namespace std;
int main()
{
int num1;
cout << "Please enter a number: ";
while (!(cin >> num1))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Try again: ";
}
}
the expression
cin >> num1
is both operative and expressive. The >> function stores input in num1 while at the same time returning a boolean value. On a successful read/store cin >> num1 returns 0 and the while loop conditional looks like this:
while(!(0)){ //code }
equivalent to
while(1){ //code }
equivalent to
while(true){ //code }
therefore when cin >> sum1 runs successfully the loop continues.
a failed read/store from cin >> num1 returns I believe 1, which evaluates to false in the while loop condition.
while(!(1)){ //code }
equivalent to
while(false){ //code }
and the loop ends here
This question already has an answer here:
C++ CIN cin skips randomly
(1 answer)
Closed 8 years ago.
Sorry, I dont know how to ask this better, I'm a really novice programmer and I'm not looking for you to do my homework, but I want to understand why this keeps happening.
int inputScores(string names [], double scores [])
{
int count = 0; // counter variable for number of student records in array
char again; // To check if user has more data
do
{
cout << "Enter student's name: ";
getline(cin, names[count]);
cout << "\nEnter student's score: ";
cin >> scores[count];
count++;
cout << "\nDo you have more student records to enter?(Y/N): ";
cin >> again;
}while(again == 'y' || again == 'Y');
when I run this code and call the function this keeps happening and I dont know how to fix it:
Enter student's name: Arthur
Enter student's score: 100
Do you have more student records to enter?(Y/N): y
Enter student's name:
Enter student's score:
it skips the "enter student's name question" (doesnt let me type anything) and goes straight to the next question.
The reason the program does not wait for you to enter the student's name is there is a \n still left in the input stream after you read again in the line:
cin >> again;
When the program reaches:
getline(cin, names[count]);
it just reads the an empty line and moves on to the next line.
You need to use:
int maxCharsToIgnore = 100; // This seems large enough
// for your use case.
cin.ignore(maxCharsToIgnore,'\n');
right after
cin >> again;
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to validate numeric input C++
How do you do the following:
while (iNumberOfPlayers <2 || iNumberOfPlayers >5)
{
cout << "Enter number of players (1-4): ";
cin >> iNumberOfPlayers;
cin.clear();
std::string s;
cin >> s;
}
After looking at the loop I'm thrown in, it looks like cin isn't getting reset (if I put in x) cin reads X again as long as I'm in the while loop. Guessing this is a buffer issue, any way to clear it?
I then tried:
while (iNumberOfPlayers <2 || iNumberOfPlayers >5)
{
cout << "Enter number of players (1-4): ";
cin >> iNumberOfPlayers;
cin.clear();
cin.ignore();
}
which works except it reads everything 1 at a time. If I put in "xyz" then the loop goes through 3 times before it stops to ask again.
If the input is not valid, the fail bit is set on the stream. The ! operator used on a stream reads the fail bit (You could also use (cin >> a).fail() or (cin >> a), cin.fail()).
Then you just have to clear the fail bit before trying again.
while (!(cin >> a)) {
// if (cin.eof()) exit(EXIT_FAILURE);
cin.clear();
std::string dummy;
cin >> dummy; // throw away garbage.
cout << "entered value is not a number";
}
Please note that if you're reading from non-interactive input, this would become an infinite loop. So use some variation on the commented error-detection code.
The tricky thing is that you need to consume any invalid input as failure to read doesn't consume the input. The simplest solution to this is to move the call to operator >> into the loop condition and then read up to the \n if it didn't mange to read an int:
#include <iostream>
#include <limits>
int main() {
int a;
while (!(std::cin >> a) || (a < 2 || a > 5)) {
std::cout << "Not an int, or wrong size, try again" << std::endl;
std::cin.clear(); // Reset error and retry
// Eat leftovers:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}