I have a very simple question that I have not been able to find the answer to anywhere. How do you determine if an integer is a legal integer value? Thanks.
I have a very simple question that I have not been able to find the answer to anywhere. How do you determine if an integer is a legal integer value? Thanks.
Well it depends on what exactly you're doing. If you try to assign the string "Hello World!" to an int, you'll get a compiler error. If you read in a character, and want to know if an integer was entered, you could check the data using the isdigit() funcion in <cctype>.
Your question is vague, but there was just a thread about this:
http://cboard.cprogramming.com/showthread.php?t=70234
Here is the final version of my code that works on a string input and handles negative numbers, overflow, octal and hex input, etc.Code:#include <sstream> #include <string> bool is_int(const std::string& s) { int i; std::istringstream istr(s); istr.unsetf(std::ios::dec); if (!(istr >> i)) return false; return istr.rdbuf()->in_avail() == 0; }