0
votes

As the beginning of my program, I am using a do-while loop to count how many inputs a user enters. The do-while loop should end after EOF (Ctrl+D) is input. My problem is however, that when I enter 1 value and then press Ctrl+D, my program says it has counted two inputs, when I want it to be only one.

#include <stdio.h>

main()
{
   int n=0;

printf("Enter values.\n");

do {
    n++;
   }
while (EOF!=scanf("%d",&n));


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

}

If I compile the program and run it, and enter a 1, then press enter, and enter Ctrl+D, it says n=2. Why is this? I only entered 1 value.

1
Because it is do..while loop. n++ will be executed before Ctrl+D is read. Easiest solution, change to while loop - GoldRoger

1 Answers

2
votes
  1. n++ is executed. n becomes 1.
  2. scanf("%d",&n) is executed. The input 1 is read.
  3. n++ is executed. n becomes 2.
  4. scanf("%d",&n) is executed. It returns EOF and break from the loop.

As a result, the result becomes 2. I think you should while statement instead of do statement in this case. Also, do not break the counter with scanf().

#include <stdio.h>

int main(void)
{
   int n=0, m;

    printf("Enter values.\n");

    while (1==scanf("%d", &m))
    {
        n++;
    }

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

    return 0;
}