scanf() in while loop not terminating?

左心房为你撑大大i 提交于 2020-01-07 01:11:30

问题


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:


  1. scanf("%d", &n) != 1 is wrong. It should be scanf("%d", &n) == 1.
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!