INT Type Checking?

Started by
4 comments, last by Dim_Yimma_H 19 years, 1 month ago
I am having the user input some command line arguments for an application but how can I make sure that the INT is an INT and that I dont assume the input is correct and risk runtime errors? I have searched the net and found many documents, none of which seem down to earth on how to go about type checking in C ! which is rather annoying. Could anyone give me a hand? (I'm using old C btw.) Thanks in advance :-)
__________Michael Dawson"IRC is just multiplayer notepad." - Reverend
Advertisement
You can get it as a string, do your check and then convert it (with atoi() or even sprintf() wich IIRC convert the string only if they contain a valid integer, in this case).
It depends on how exacting you need to be.

The simple thing to do is to just call atoi and be done with it.

The next level of sophistication would be to walk the string and call isdigit on each character. If they all pass then call atoi to do the conversion.

From there it depends on your exact requirements. You might want to ignore whitespace at the beginning/end of the string for example.
-Mike
strtol can also do a lot of error checking for you.
int main(int argc, char **argv) { long value; char *endptr; if(argc < 2) {  /* not enough arguments */ } value = strtol(argv[1], &endptr, 10); if(*endptr) {  /* syntax error */ } if(value <= INT_MIN || value >= INT_MAX) {  /* out of range */ } ...}
It still doesn't complain about initial whitespace but it's usually close enough. A neat feature is to change radix to zero and let the function handle hexadecimal constants automatically, but it's somewhat dangerous since most users won't expect numbers prefixed with a zero to be interpreted as octal.
Well if the type is int, it's an int, it'll cut of the decimal and anything over it's limit. but if you have the chance of something else being passed in and you want a very fast way to make sure it's a whole number?

if(x<0)
x==-abs(x);
else
x==abs(x)
Also, if your'e using the iostream library and the cin function then you could check if there was an input error.

double d;

cin >>d; //try and input a double

if (!cin.good()) //there was an input error
{
cin.clear(); //clear the error flag so it's possible to input again
cin.ignore(255, '\n'); //remove 255 characters or
//until the last '\n' is found (the bad input is removed)
}

The error flag will be set for instance if you try to input some characters into the double.

\Jimmy H

edit: the code above requires the current used namespace to be defined:
using namespace std;
Or you could just write std::cin every time cin is called.
Also, maybe I should note that cin is not really a function, it's an instance of the class istream and they've overloaded the >> operator so it can be called like a function.

This topic is closed to new replies.

Advertisement