You ignore the return from scanf() , which tells you if the conversion information ( %d ) was accurate or not. If this was inaccurate, you need to perform error recovery, which is not very convenient with scanf() . Most people use the βread the input line and then parse itβ approach, where error recovery is easier.
I understand that return values ββare necessary for checking errors, but how do I scan their numbers or letters? Can I say if (input! = (Integers)) or something like that?
This is why people do not use scanf() . If you get a string of data into the buffer (an array of characters), you can check the contents of the array as often as you like. If you use scanf() , you have no reliable ability to process the data until after scanf() decides that it has an error.
Functions (usually also available as macros) in <ctype.h> allow you to classify characters. The functions in <stdlib.h> provide robust conversions from strings to integers of various types.
So you can think of doing something like:
char buffer[256]; while (fgets(buffer, sizeof(buffer), stdin)) { ...check contents of buffer using isdigit() etc... ...or just plough ahead with... long value; char *end; errno = 0; value = strtol(buffer, &end, 0); if (errno != 0 || (*end != '\0' && !isspace(*end)) ...diagnose problems... }
This code is a bit out of my league at the moment .. is there an easier way?
Well, I suppose you can use atoi() instead of strtol() , which simplifies error handling (because it is less accurate):
char buffer[256]; while (fgets(buffer, sizeof(buffer), stdin)) { int value = atoi(buffer); if (value == 0) { puts("zero read - exiting loop"); break; } }
It is not much easier. I do not know what part of the previous decision you considered outside of you. The alternatives, it seems to me, are very confusing, including reading one character at a time and saving numbers and discarding numbers:
char buffer[256]; char *dst = buffer; int c; int value; while ((c = getchar()) != EOF) { if (isdigit(c)) { *dst++ = c; } else if (isspace(c)) { *dst = '\0'; value = atoi(buffer); break; } else { printf("Unexpected character '%c'!\n", c); } }
Etcetera. There are various problems in this code - for example, resetting the pointer after an erroneous character and eliminating buffer overflows, as well as accessing signs on numbers and ... well, all kinds of things that I prefer to leave to subroutines, for example, fgets() and strtol() .