2

I am new to C Programming and Ubuntu. I was reading the "The C Programming Language" by D.M Ritchie where I found the following code:

#include <stdio.h>

int main()
{
    int c;
    int nc=0;
    while((c = getchar()) != EOF)
    {
        nc++;
    }

    printf("%d Characters \n",nc);

    return 0;
}

But while running the program I enter "Hello" ,then CTRL+D twice to get the actual number of characters which is 5.

But when I enter "Hello" then CTRL+D once, nothing happens, the terminal still waits for input.

Why?

  • I think that CTRL+D sends `EOF` if there isn't any data to be flushed into the `stdin`. – Spikatrix May 09 '15 at 07:52
  • http://stackoverflow.com/questions/29746522/why-is-some-code-from-kr-not-working-in-codeblocks/29746577#comment47630286_29746577 – Spikatrix May 09 '15 at 07:57
  • @CoolGuy I followed the above link and found the comment of Veritas to be helpful. Thanks for your help. But if I press "ENTER" after "Hello" and then CTRL+D once , the character count becomes 6. I think it takes "\n" to be an extra character in addition to 'Hello'. Isn't ? – Soumyadeep Ganguly May 09 '15 at 08:07
  • Yes. That's right. Remember that `EOF != '\n'`. So the loop won't break when you press the enter key. – Spikatrix May 09 '15 at 08:10
  • I now tried the following code .... #include int main() { char c; c=getchar(); while (c!= EOF) { putchar(c); c=getchar(); } return 0; } The above code shows the input as output... Here when I press "ENTER" the loop breaks after showing the output as expected.. When EOF!= "\n" How this happens? Here I don't have to press CTRL+D at all!! – Soumyadeep Ganguly May 09 '15 at 08:36
  • @SoumyadeepGanguly , `c` should be an `int`. I suggest you post a new question if you have any. – Spikatrix May 09 '15 at 08:49

1 Answers1

2

Quoting @Veritas's comment,

On linux Ctrl-D only works when the buffer is already empty otherwise it just flushes it. Therefore unless he has pressed enter without any characters after that, he will have to press Ctrl-D twice.

This explains the issue. You have to press it twice because you , after typing Hello, did not press the Enter to flush the input into the stdin. So the first time you press CTRL+D, it flushes the data into the stdin. The second time you press it, EOF is sent.

Community
  • 1
  • 1
Spikatrix
  • 20,225
  • 7
  • 37
  • 83