1
if (fgets(string, 35, stdin)==NULL)

It only works when I just use ctrl+D.

It will print

"what I want"

and exit.

But, if I type

'abc'

and don't press Enter, then ctrl+D.

It doesn't work, and continue to run again until I use ctrl+D second time.

Can you give me some idea?

TryinHard
  • 4,078
  • 3
  • 28
  • 54
Zheng Lu
  • 33
  • 2
  • Different OS's and keyboard interfaces have different ways to generate `EOF`. Post your OS details. – chux - Reinstate Monica Aug 21 '15 at 04:00
  • This is normal behavior for most Unix OSes - I'm going to post an answer on this assumption (since it wouldn't be typical for a non-Unix user to expect ctrl-D to work) – Random832 Aug 21 '15 at 04:35
  • 3
    possible duplicate of [ctrl-d didn't stop the while(getchar()!=EOF) loop](http://stackoverflow.com/questions/11944314/ctrl-d-didnt-stop-the-whilegetchar-eof-loop) – user12205 Aug 21 '15 at 04:51

1 Answers1

2

This is normal behavior - when you type it after already typing some characters on the line, it allows the process to read the characters you've typed (you'll notice that you can't backspace past this point, and if you do it in e.g. cat the characters you typed may be echoed immediately)

The relevant Unix standard can be found here:

EOF

Special character on input, which is recognized if the ICANON flag is set. When received, all the bytes waiting to be read are immediately passed to the process without waiting for a < newline >, and the EOF is discarded. Thus, if there are no bytes waiting (that is, the EOF occurred at the beginning of a line), a byte count of zero shall be returned from the read(), representing an end-of-file indication. If ICANON is set, the EOF character shall be discarded when processed.

Basically, ctrl-D in the middle of the line isn't "really" the end of the file, and there's no reason to expect to detect it. If you want to end standard input without a final newline, just press ctrl-D twice.

alk
  • 69,737
  • 10
  • 105
  • 255
Random832
  • 37,415
  • 3
  • 44
  • 63
  • 1
    @ZhengLu It is simply impossible unless your program captures keyboard events directly. – user12205 Aug 21 '15 at 06:59
  • Try showing your teacher this standard and asking if this includes if they press ctrl-D in the middle of a line. They probably didn't even think of it. – Random832 Aug 21 '15 at 17:53