In class I need to use scanf
to get integers to work with. Problem is I do not know to end the while
loop. I wait for \'\\n\'
in the c
while(scanf("%d%c", &numbers, &ch)) { if((ch == '\n') ....
has a couple of problems.
If the line of input has only white-space like "\n"
or " \n"
, scanf()
does not return until non-white-space is entered as all leading white-spaces are consumed by "%d"
.
If space occurs after the int
, the "\n"
is not detected as in "123 \n"
.
Non-white-space after the int
is discarded as in "123-456\n"
or "123x456\n"
.
how to end loop?
Look for the '\n'
. Do not let "%d"
quietly consume it.
Usually using fgets()
to read a line affords the more robust code, yet sticking with scanf()
the goal is to examine leading white-space for the '\n'
#include <ctype.h>
#include <stdio.h>
// Get one `int`, as able from a partial line.
// Return status:
// 1: Success.
// 0: Unexpected non-numeric character encountered. It remains unread.
// EOF: end of file or input error occurred.
// '\n': End of line.
// Note: no guards against overflow.
int get_int(int *dest) {
int ch;
while (isspace((ch = fgetc(stdin)))) {
if (ch == '\n') return '\n';
}
if (ch == EOF) return EOF;
ungetc(ch, stdin);
int scan_count = scanf("%d", dest);
return scan_count;
}
Test code
int main(void) {
unsigned int_count = 0;
int scan_count;
int value;
while ((scan_count = get_int(&value)) == 1) {
printf("%u: %d\n", ++int_count, value);
}
switch (scan_count) {
case '\n': printf("Normal end of line.\n"); break;
case EOF: printf("Normal EOF.\n"); break;
case 0: printf("Offending character code %d encountered.\n", fgetc(stdin)); break;
}
}