2

I'm trying to scan in tokens lineated by whitespace.

    while(scanf(" %s ", input) != EOF){
        printf("%s", input);
    }

If I type in:

ggh ghk kfj

My program will output:

gghghk

And once pressing Ctrl-D, it will then display:

gghghkkfj

I want my program to output: ggh (Ctrl-D) ghk (Ctrl-D) and then kfj (Ctrl-D)

Please help.

Thomas Guillerme
  • 1,747
  • 4
  • 16
  • 23
mcfluff
  • 21
  • 2
  • 3
    There is no need to use leading whitespace with `%s`, which _automatically_ ignores leading whitespace characters. And you should _not_ use trailing whitespace characters in `scanf()` format strings. This causes trouble with interactive input because it skips whitespace characters _until a non-whitespace character or end-of-file is encountered_. – ad absurdum Feb 27 '18 at 02:36
  • Short answer: don't use `scanf` for this. This functions was not design for this kind of use. Use `fgets` instead. – Pablo Feb 27 '18 at 02:37
  • You are running up against 2 problems. (1) if you type `ggh` and press `ctrl+d` - nothing happens. Why? You have indicated that you are done with input (and there are characters to read), but the `%s` conversion is not complete (it has not encountered a whitespace). So (2), you have to press `ctrl+d` again to force the return of `EOF` (`feof` set) because this time there are no characters to read when you trigger `EOF`. If you enter `ggh ghk kfj` and then press `ctrl+d`, you get `gghghk` because now `%s` completes on each `' '` and finally `scanf` is blocking on `kjf`. (not the way to go) – David C. Rankin Feb 27 '18 at 06:23

0 Answers0