0

I am attempting to check whether certain variables read in from a file are integers are not, and if they aren't ignore them and go on with the printing of an error message. So I am using isdigit() to see if the variables are ints or not and it keeps working "backwards" in a sense.

int parseStudent(struct student *person, char *data){

char *ptr;
int temp;

int i = 0;

ptr = strtok(data, DELIM);

temp = atoi(ptr);

if(isdigit(temp)){printf("Invalid TERM integer!\n");}

//if(!isdigit(temp)){printf("Invalid TERM integer!\n");}


//person[i].term = temp;


ptr = strtok(NULL, DELIM);

person[i].id = atoi(ptr);


ptr = strtok(NULL, DELIM);

strcpy(person[i].lastname, ptr);


ptr = strtok(NULL, DELIM);

strcpy(person[i].firstname, ptr);


ptr = strtok(NULL, DELIM);

strcpy(person[i].subjectname, ptr);


ptr = strtok(NULL, DELIM);

person[i].catalog = atoi(ptr);


ptr = strtok(NULL, DELIM);

strcpy(person[i].section, ptr);

}

Now as you can see with my first check my intent is to see if that first temp int (which is suppose to hold an int, it does "1301") is in fact an integer. When I use the uncommented line, it fails the condition and nothing is printed. When I use the commented line it prints my error message. Isn't that backwards!? How do I check these ints and strings to in fact be ints and strings and report errors on the face?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Sherifftwinkie
  • 391
  • 1
  • 13
  • 21

3 Answers3

3

isdigit belongs to character classification functions. So this function will interpret the value returned by atoi as a character (using your charset, such as ASCII). It won't be what you expect. If you want to handle errors, you can read this answer.

Community
  • 1
  • 1
md5
  • 23,373
  • 3
  • 44
  • 93
  • This is completely wrong... `atoi(3)` takes a _string_ and interprets it as a decimal number (if possible). Whatever `atoi` returns, it isn't a `char` to which `isdigit(3)` applies. – vonbrand Mar 05 '13 at 20:30
3

isdigit - check the documentation - it is supposed to be used on character variables, not integer-value variables.

Check it out:

char digit = '1';
char notDigit = 'a';
char notEvenCloseADigit = 1;
int digitIsDigit = isdigit(digit);
int notDigitIsDigit = isdigit(notDigit);
int notEvenCloseADigitIsDigit= isdigit(notEvenCloseADigit);
Dariusz
  • 21,561
  • 9
  • 74
  • 114
  • 1
    Perhaps you should rather speak about "characters" and "integers" instead of `char` and `int`, since `'1'` has `int` type. – md5 Mar 05 '13 at 18:13
  • @Kirilenko done, you're right; that's what I meant and I hope that's how I was understood. – Dariusz Mar 05 '13 at 18:27
0

this is not backwards. isDigit returns true if it is a digit, which you said you used "1301". So your uncommented line is returning true. The later, however, takes !true, or false.

75inchpianist
  • 4,112
  • 1
  • 21
  • 39