user1148809
user1148809

Reputation:

scanf() in while loop not terminating?

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?

Upvotes: 0

Views: 5745

Answers (1)

melpomene
melpomene

Reputation: 85767

  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.)

Upvotes: 6

Related Questions