0% found this document useful (0 votes)
88 views

C++ Test If Input Is An Double - Char - Stack Overflow

This document discusses ways to check if user input is a double or char in C++. It notes that directly reading input into a double can cause issues if the input is not a valid double. Better approaches suggested include: 1. Read all input as strings then check if it can be converted to a double/char. 2. For doubles, use strtod() to convert the string and check for conversion errors. 3. For chars, check the string length is 1 after reading the full line of input. Reading the entire line of input as a string first allows for better validation and error handling when checking the type of user input.

Uploaded by

ADJANOHOUN jean
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
88 views

C++ Test If Input Is An Double - Char - Stack Overflow

This document discusses ways to check if user input is a double or char in C++. It notes that directly reading input into a double can cause issues if the input is not a valid double. Better approaches suggested include: 1. Read all input as strings then check if it can be converted to a double/char. 2. For doubles, use strtod() to convert the string and check for conversion errors. 3. For chars, check the string length is 1 after reading the full line of input. Reading the entire line of input as a string first allows for better validation and error handling when checking the type of user input.

Uploaded by

ADJANOHOUN jean
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

C++ test if input is an double/char - Stack Overflow https://stackoverflow.com/questions/2065392/c-test-if-i...

C++ test if input is an double/char


Asked 11 years, 7 months ago Active 11 years, 7 months ago Viewed 16k times

I am trying to get input from the user and need to know a way to have the program
recognize that the input was or was not a double/char this is what i have right now... but
0 when you type an incorrect type of input

1) the double test one just loops infinatly

2) the char one won't stop looping even with the correct imput
1

int main () {
double _double = 0;
bool done = true;
while ( done ) {
cout << "Please enter a DOUBLE:\n" << endl;
cin >> _double;
if ( _double > 0 ) { done = false; }
if ( _double < 0 ) { cout << "\nthe number you entered was less than
zero\nplease enter a valad number..." << endl; }
if(cin.fail()) { cin.clear(); }
}

done = false;
char _char = ' ';
while ( !done ) {
cout << "Please enter a CHAR" << "\n";
cout << "\t'y' = yes\n\t'n' = no" << endl;
cin >> _char;
if ( _char == 'y' || _char == 'n' ) { done = true; }
if ( ! (_char == 'y' || _char == 'n') ) { cout << "\nyou have entered an
invald symbol... \n" << endl; }
if(cin.fail()) { cin.clear(); }
}

c++ input loops

Share Edit Follow edited Jan 14 '10 at 16:24 asked Jan 14 '10 at 15:50
Wallter
4,175 6 27 33

2 And it doesn't work? Could you please specify output, and expected output? It gets you answers
quicker. – Skurmedel Jan 14 '10 at 15:52

1 Any char you input is a char, obviously. How could that test possibly fail? The code suggests you're
looking for a specific char, in particular either 'y' or 'n' . – MSalters Jan 14 '10 at 16:24

3 Answers Active Oldest Votes

1 sur 4 10/08/2021 à 14:59


C++ test if input is an double/char - Stack Overflow https://stackoverflow.com/questions/2065392/c-test-if-i...

The problem is that when you read something and cin sees the input can never be a
double, it stops reading, leaving the stuff in the buffer that it didn't consume. It will signal
3 failure, which you clear but you won't eat the remaining input that cin didn't eat up. So, the
next time the same wrong input is tried to read again, and again...

The problem with the char one is that you have to press the return key to make it process
any characters on most terminals (this does not happen if you make your program read
from a file, for instance). So if you press y then it won't go out of the read call, until you hit
the return key. However, then it will normally proceed and exit the loop.

As others mentioned you are better off with reading a whole line, and then decide what to
do. You can also check the number with C++ streams instead of C functions:

bool checkForDouble(std::string const& s) {


std::istringstream ss(s);
double d;
return (ss >> d) && (ss >> std::ws).eof();
}

This reads any initial double number and then any remaining whitespace. If it then hit eof
(end of the file/stream), it means the string contained only a double.

std::string line;
while(!getline(std::cin, line) || !checkForDouble(line))
std::cout << "Please enter a double instead" << std::endl;

For the char, you can just test for length 1

std::string line;
while(!getline(std::cin, line) || line.size() != 1)
std::cout << "Please enter a double instead" << std::endl;

If you want to read only 1 char and continue as soon as that char was typed, then you will
have to use platform dependent functions (C++ won't provide them as standard functions).
Look out for the conio.h file for windows for instance, which has the _getch function for
this. On unix systems, ncurses provides such functionality.

Share Edit Follow answered Jan 14 '10 at 16:39


Johannes Schaub - litb
469k 117 854 1178

WOW 'Johannes Schaub - litb', thank you so much! you have no idea how much time you saved
me. thank you! – Wallter Jan 14 '10 at 18:47

2 sur 4 10/08/2021 à 14:59


C++ test if input is an double/char - Stack Overflow https://stackoverflow.com/questions/2065392/c-test-if-i...

The best bet is always to read your input as strings. You can then use functions like
std::strtod() to test and convert to doubles. Checking if streams have failed and then
5 resetting them is error prone at best, and doesn't give you the possibility of producing good
error messages.

For example:

string s;
cin >> s;
char * p;
double d = strtod( s.c_str(), & p );
if ( * p == 0 ) {
cout << "Read double: " << d << endl;
}
else {
cout << "Read string: " << s << endl;
}

The pointer 'p' will point to the first character that cannot be converted to a double. How
exactly you handle that really depends on your app's logic.

Share Edit Follow edited Jan 14 '10 at 16:06 answered Jan 14 '10 at 15:57
anon

cin >> _double will always get you a double, whether they typed in "42", "0" or "mary had
a little lamb". You need to read the user input as a string, then test that string to see if it is a
2 double. sscanf will return 0 if it can't convert the input string to the desired type:

cout << "Please enter a DOUBLE:\n" << endl;


string s;
cin >> s;
if( !sscanf(s.c_str(), "%lf", &_double) )
{
done = false;
cout << "Not a number, sparky. Try again." << endl;
continue;
}

Also, identifiers with leading underscores like you have are reserved by the language. Don't
get in the habit of naming things like _double -- someday, they may not work.

Share Edit Follow edited Jan 14 '10 at 18:50 answered Jan 14 '10 at 16:06
John Dibling
94.7k 27 174 305

3 sur 4 10/08/2021 à 14:59


C++ test if input is an double/char - Stack Overflow https://stackoverflow.com/questions/2065392/c-test-if-i...

haha yeah the '_' was just to give a more concise example of the source – Wallter Jan 14 '10 at
16:12

Actually, you can test the result of cin >> _double : if(cin >> _double) done=true; else
cout << "Not a number!" << endl; – Adam Bowen Jan 14 '10 at 16:35

The format specifier is wrong, it must be "%lf". Using "%f" stuffs a float in a double. This is kinda like
the worst of both. – Hans Passant Jan 14 '10 at 18:42

4 sur 4 10/08/2021 à 14:59

You might also like