0

I'm reading from stdin into an array input[], but it never leaves the loop after reading the input and keeps expecting more input. What am I doing wrong?

        char input[1000];
        while(scanf("%s",input)==1){
            printf("%s\n",input);
        }
book
  • 11
  • 1
  • 5
  • 1
    Read this: https://stackoverflow.com/questions/10469643/value-returned-by-scanf-function-in-c and https://stackoverflow.com/questions/3197025/end-of-fileeof-of-standard-input-stream-stdin – รยקคгรђשค Jan 14 '18 at 02:56
  • 2
    `scanf` returns the number of input items successfully matched and assigned. `%s` matches a sequence of non-white-space characters, aka your first word, but leaves the newline `\n` in the buffer. `scanf` returns 1. After that it reads the newline and returns one, then you input a second word, etc etc etc. You see the loop? – Pablo Jan 14 '18 at 03:06
  • Should have an OS tag here. – Joshua Jan 14 '18 at 03:08
  • What do you want the user to type to indicate the end of input? – Barmar Jan 14 '18 at 03:20

2 Answers2

0

What you expect, how do you try to terminate it? scanf("%s", input) keeps waiting input always and always returns 1 if stdin is life, it skips whitespaces and matches the first char sequence without whitespaces. Please read the manual carefully.

If you want to continue scanf using then you should provide a special string for breaking the loop.

273K
  • 29,503
  • 10
  • 41
  • 64
0

Since scanf() returns **the number of elements successfully read, you must find a way to make it fail to read the %s. One common practice is to end the input with EOF, which is Ctrl-Z then Enter in Windows console, and Ctrl-D on a Unix terminal. After reading EOF scanf() will return EOF which is of course not 1, then the loop exits normally.

Alternatively, you can use a custom terminating string in your code:

    char input[1000];
    while (scanf("%s", input) == 1) {
        if (strcmp(input, "end") == 0) {
            // End the loop
            break;
        }
        printf("%s\n", input);
    }
iBug
  • 35,554
  • 7
  • 89
  • 134