Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isdigit() c++, probably simple question, but stuck

Tags:

c++

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;
}
like image 413
Crystal Avatar asked Jun 03 '10 23:06

Crystal


1 Answers

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., the std::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:

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

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

if (std::cin >> k)

and the result will be the same.

like image 185
James McNellis Avatar answered Sep 21 '22 15:09

James McNellis