问题
I have a while loop that scans in an input set of integers. It scans and prints all of the numbers with "..." at the end and skips to the next line. However, the script does not: execute past the while loop and print TEST.
For example, I enter: 3 44 62 1
It prints: 3...
44...
62...
1...
When it should print: 3...
44...
62...
1...
TEST
while(scanf("%d", &n) != -1) {
x[i] = n;
i++;
printf("%d", n);
printf("...\n");
}
printf("TEST");
What am I doing wrong?
回答1:
scanf("%d", &n) != 1
is wrong. It should bescanf("%d", &n) == 1
.- You're expecting the loop to end just because you hit enter? As written, your program will only stop if scanf fails to read a number due to reaching the end of the input file. If you're on Unix, you can signal EOF from the terminal by hitting Ctrl-D. If you're on Windows, it's Ctrl-Z Enter. (Also, don't rely on
EOF
being -1; it's not portable.)
来源:https://stackoverflow.com/questions/13549102/scanf-in-while-loop-not-terminating