while(scanf("%d%c", &numbers, &ch)) { if((ch == '
') ....
has a couple of problems.
If the line of input has only white-space like "
"
or "
"
, 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 "
"
is not detected as in "123
"
.
Non-white-space after the int
is discarded as in "123-456
"
or "123x456
"
.
how to end loop?
Look for the '
'
. 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 '
'
#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.
// '
': End of line.
// Note: no guards against overflow.
int get_int(int *dest) {
int ch;
while (isspace((ch = fgetc(stdin)))) {
if (ch == '
') return '
';
}
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
", ++int_count, value);
}
switch (scan_count) {
case '
': printf("Normal end of line.
"); break;
case EOF: printf("Normal EOF.
"); break;
case 0: printf("Offending character code %d encountered.
", fgetc(stdin)); break;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…