The program asks for a number. The program should loop the scanf() function if the user types anything else other than numbers.
The code is,
do{
printf("Enter row number\n");
scanf("%d",&row);
}while(row>='a' && row<='z');
But the above code doesn’t work. I keep getting an error when typing in a letter. I tried manipulating around it and the whole thing loops infinitely.
Any suggestions?
Also how can I tell the C Compiler not to break the loop unless the input is an INTEGER?
You are ignoring the return from
scanf()which tells you whether the typed information was accurate for the conversion (%d) or not. If it was inaccurate, you have to do error recovery, which is not particularly easy withscanf(). Most people go for the approach of ‘read a line of input and then parse it’, where the error recovery is simpler.This is why people don’t use
scanf(). If you get the line of data into a buffer (character array), then you can check the contents of the array as often as you like. If you usescanf(), you don’t get a reliable chance to process the data until afterscanf()decides it has an error.The functions (usually also available as macros) in
<ctype.h>allow you to classify characters. The functions in<stdlib.h>provide reliable conversions from strings to integers of various sorts.So, you can think about doing something like:
Well, I suppose you can use
atoi()instead ofstrtol(), which simplifies the error handling (because it is less precise):It doesn’t get much simpler than this. I don’t know which part of the previous solution you felt was beyond you. The alternatives, it seems to me, are much fiddlier, involving reading one character at a time and saving the digits and rejecting the non-digits:
Etcetera. There are various issues to resolve in that code – like resetting the pointer after an erroneous character, and avoiding buffer overflow, and dealing with signs on the numbers, and … well, all sorts of stuff that I’d rather leave to routines like
fgets()andstrtol().