how do I test for type char on input
There are several mechanisms to use. You might consider these 2:
Style 1.
The 'c' style would be to check every input char with isdigit().
i.e. Read user input into a string, check that each char is a digit, etc.
std::cout << "Enter a number: ";
std::string user_input;
std::cin >> user_input;
for (int i=0; i<user_int.size(); i++
if (!isdigit(user_input[i])
throw "not a digit";
// if you get here, all the chars in user_input are digits,
// I suppose you might use atoi() to convert, but see next.
Note - there is also a hex check, isxdigit(). And if you want to allow the user to input commas or space chars, you can use user_input.erase(...) for each single char you wish to allow the user to use, but ignore as part of the number.
Style 2.
You may prefer the c++ style, which I find easier, but requires getting comfortable with C++ std::string methods.
std::cout << "Enter a number: ";
std::string user_input;
std::cin >> user_input;
const char* DIGITS = "0123456789";
size_t notaDigit = user_input.find_first_not_of(DIGITS);
if(notaDigit != std::string::npos)
throw "non-digit char found in user_input";
// if you get here, all chars are digits, so convert to integer.
// these days, I would do this in 4 steps.
int user_int = 0;
{
std::stringstream ss;
ss << user_input; // put char string into ss
ss >> user_int; // extract and convert to integer
} // discard and cleanup the stringstream at scope end
std::cout << "user_int: " << user_int << std::endl;
if a char input is received (not sure about string) that it is converted to int
FYI - I was unable to reproduce this on gcc 4.8.1 on ubuntu 12.04.
Character inputs thru std::cin do not convert to int.
The conversion attempt stops converting digit's into part of the integer at the first non-digit char. Thus, a 33Y will convert to 33, because it stopped converting at the Y. An ABC input, (or AB input, or A input,) will stop converting at the first (non-digit) char, thus the conversion reports 0.
I believe that that certain conversion attempts (from string to POD) can also set flags on the istream, but did not check.
Examples:
dmoen@C5:~/cvs-tools/lmbm/src_ut$ ./dmy24
Enter a number: 12
0
1
2
3
4
5
6
7
8
9
10
11
12
dmoen@DOMA5:~/cvs-tools/lmbm/src_ut$ ./dmy24
Enter a number: a
0
dmoen@DOMA5:~/cvs-tools/lmbm/src_ut$ ./dmy24
Enter a number: bcd
0
dmoen@DOMA5:~/cvs-tools/lmbm/src_ut$ ./dmy24
Enter a number: ABC
0
Note that most C-style functions automagically promote a char into an int. For example, the input to isdigit() is declared to be an int, so the promotion makes it easier to use.
C++ also supports this promotion, but I would guess that is not what you were seeing.