For loop iteration issue

92 Views Asked by At

I have tried many variations of this code, including using a scanf function, and every time it increments by 2 points instead of one. Here is the code:

#include <stdio.h>
int main(void)
{
    double nc;
    for(nc = 0; getchar() != EOF; ++nc)
          printf("%.0f\n", nc);
}

This is the output that I get. The input that I used was qwerty, and the outputs are numbers 0-11 instead of 0-5 as expected.

q 
0
1
w
2
3
e
4
5
r
6
7
t
8
9
y
10 
11

One thought I had was that when I press enter, it is counted as a value for getchar along with the character I entered and this causes the loop to run through two iterations. Can anybody further explain this concept or provide links to more information about it for me?

1

There are 1 best solutions below

0
On

The trailing newline from previous getchar is taken up as input for next getchar

So use,

   for(nc = 0; getchar() != EOF; ++nc)
      {
       printf("%.0f\n", nc);
       getchar(); //"eat" the trailing newline
      }