I’m having trouble with isdigit. I read the documentation, but when I cout << isdigit(9), I get a 0. Shouldn’t I get a 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 (e.g. 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;
}
isdigit()is for testing whether a character is a digit character.If you called it as
isdigit('9'), it would return nonzero.In the ASCII character set (which you are likely using), 9 represents the horizontal tab, which is not a digit.
Since you are using the I/O streams for input, you don’t need to use
isdigit()to validate the input. The extraction (i.e., thestd::cin >> k) will fail if the data read from the stream is not valid, so if you are expecting to read an int and the user enters “asdf” then the extraction will fail.If the extraction fails, then the fail bit on the stream will be set. You can test for this and handle the error:
Note that the extraction itself also returns the stream, so you can shorten the first two lines to be simply:
and the result will be the same.