TheCaptain
TheCaptain

Reputation: 135

C programming — loop

I am following the exercises in the C language book. I am in the first chapter where he introduces loops. In this code:

#include <stdio.h>

/* copy input to output; 1st version */

int main() {
  int c, n1;

  n1 = 0;
  while ((c = getchar()) != EOF) {
    if (c == '\n') {
      ++n1;
    }
    printf("%d\n", n1);
  }
}

In here I am counting the number of lines. When I just hit enter without entering anything else I get the right number of lines but when I enter a character then hit enter key the loop runs twice without asking for an input the second time. I get two outputs. this how the output looks like:

   // I only hit enter
1
   // I only hit enter
2
   // I only hit enter
3
g // I put char 'g' then hit enter
3
4

3 and 4 print at the same time. why is 4 printing after the loop has been iterated already? I thought the loop would restart and ask me for input before printing 4.

Upvotes: 1

Views: 319

Answers (2)

user2736738
user2736738

Reputation: 30936

To be clear this is the terminal that you are dealing with.

By default, the terminal will not get input from the user \n is entered. Then the whole line is placed in the stdin.

Now as I said earlier here the program is not affected by the buffering of stdin. And then the characters will be taken as input and it is processed as you expect it to be. The only hitch was the terminals buffering - line buffering.

And here from standard you will see how getchar behaves:-

The getchar function returns the next character from the input stream pointed to by stdin. If the stream is at end-of-file, the end-of-file indicator for the stream is set and getchar returns EOF. If a read error occurs, the error indicator for the stream is set and getchar returns EOF.

Now what are those characters - those charaacters include \n - the \n is what you put in the terminal and then to stdin via pressing the ENTER. Here earlier you were entering the characters earlier which were \n. This time you entered two characters. That's why the behavior you saw.

Upvotes: 1

haccks
haccks

Reputation: 106102

The getchar function reads one character at a time. The number of lines will be printed for every character in the input read by getchar, whether that character is newline or not, but the counter will only be incremented when there is a newline character in the input.

When you enter g then the actual input that goes to the standard input is g\n, and getchar will read this input in two iterations and that's the reason it is printing number of lines twice.

If you put the print statement inside the if block then it will print only for newline characters. If you put the print statement outside the loop, then it will only print the count of the number of lines at the end of the input.

Upvotes: 2

Related Questions