-
Using cin correctly
I'm writing a program that takes an integer input via 'cin'.
I want to make the program to make sure the number is not a character or string (which would cause the program to crash)
So far.. this is the code I have..
Code:
int getUserTempInput()
{
int x = 0;
while (x != 1)
{
cout << "\nEnter a temperature to convert: \n";
cin >> userTemp;
if (cin.good() == true)
{
x = 1;
}else{
cout << userTemp << " is not a valid integer. Please try again.\n\n" << endl;
}
} //end while loop
return userTemp;
} //end getUserInput
When i execute the program, and try to enter something like:
ssdfsdf sdfsdfs fsw
the program goes into an infinate loop. I looked on google and read something about using 'boolean cin.good()' and tried it in the code, but it doesn't seem to help.
What function could I use to insure that the correct input is taken in?
Thanks.
-
In general, read user input as a string, then later convert. If this option is not available to you, look in the FAQ.
-
One idea is to use cin.clear to clear the flags and cin.ignore to clear the input buffer.
Code:
#include <iostream>
#include <limits>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int input;
while (cout << "Enter a number: " && !(cin >> input))
{
cout << "\nInvalid input" <<endl;
cin.clear();
cin.ignore(std::numeric_limits < int >::max(), '\n');
}
cout <<"You entered " <<input;
}
This code is copied from the (FAQ) entry found here:
http://faq.cprogramming.com/cgi-bin/...&id=1043284392
-
you can check for a char (not string) using isascii (int c)
-
>you can check for a char (not string) using isascii (int c)
The input stream will already be in a failure state at this point, so your solution won't work unless the type of the input variable is some form of char or string. It seems that the problem is (a common one) where people expect cin to somehow not fail when trying to read the wrong type of value.