Isdigit () C ++, maybe a simple question, but stuck

I have problems with isdigit. I read the documentation, but when I cout <isdigit (9), I get 0. Should I get 1?

#include <iostream> #include <cctype> #include "Point.h" int main() { std::cout << isdigit(9) << isdigit(1.2) << isdigit('c'); // create <int>i and <double>j Points Point<int> i(5, 4); Point<double> *j = new Point<double> (5.2, 3.3); // display i and j std::cout << "Point i (5, 4): " << i << '\n'; std::cout << "Point j (5.2, 3.3): " << *j << '\n'; // Note: need to use explicit declaration for classes Point<int> k; std::cout << "Enter Point data (eg number, enter, number, enter): " << '\n' << "If data is valid for point, will print out new point. If not, will not " << "print out anything."; std::cin >> k; std::cout << k; delete j; } 
+7
c ++
source share
3 answers

isdigit() is for checking if a character is a digit character.

If you named it as isdigit('9') , it will return a nonzero value.

In the ASCII character set (which you most likely use), 9 is a horizontal tab that is not a digit.


Since you use input / output streams for input, you do not need to use isdigit() to validate the input. The extraction (i.e. std::cin >> k ) will fail if the data read from the stream is invalid, so if you expect to read the int and the user enters "asdf", the extraction will fail.

If the extraction fails, the error bit in the stream will be set. You can check this and handle the error:

 std::cin >> k; if (std::cin) { // extraction succeeded; use the k } else { // extraction failed; do error handling } 

Note that the extraction itself also returns a stream, so you can simply shorten the first two lines:

 if (std::cin >> k) 

and the result will be the same.

+16
source share

isdigit() takes an int , which is a representation of the character. Character 9 (assuming you are using ASCII) is a TAB character. The character 0x39 or '9' (not 9) is the actual character representing the number 9.

Digit characters are integer codes from 0x30 to 0x39 (or 48 to 57) in ASCII - I repeat that, since ASCII is not a requirement of the ISO C standard. Therefore, the following code:

 if ((c >= 0x30) && (c <= 0x39)) 

which I saw earlier is not a good idea for portability, since there is at least one implementation using EBCDIC under covers - isdigit is the best option in all situations.

+5
source share

isdigit() works with characters, not the ascii values ​​that you are currently passing. Try using isdigit('9') .

0
source share

All Articles