Why does while((c = getchar()) != EOF) repeat 2 times in c programming?

95 Views Asked by At

When I enter a number from keyboard, while loop goes 2 times, and I didn't understand why it is doing that. I want to run this loop for one time after each entering number. Is there anyone who can explain this situation?

My code:

#include <stdio.h>

int main() {
    char c;
    
    while((c = getchar()) != EOF){
        printf("c = %c\n", c);
        
        int i;
        for(i = 0; i< 10; i++){
            printf("%d in loop\n", i);
        }
    }
    
    printf("%d - at EOF\n", c);
}

Output: enter image description here

I want to make this source code work truly.

1

There are 1 best solutions below

0
chux - Reinstate Monica On

why does while((c = getchar()) != EOF) repeat 2 times in c programming (?)

Because OP pressed 2 keys: 6 and Enter before signaling end-of-file.
The for loop ran once for each character: '6' and '\n'.


I want to run this loop for one time after each entering number.

It appears OP wants to run the loop per each digit.
Amend code to only run the loop when the key is a digit:

if (c >= '0' && c <= '9') { // add
    for (i = 0; i< 10; i++) {
        printf("%d in loop\n", i);
    }
} // add

Or use if (isdigit(c)) {.

Additional code needed if input like - 1 2 3 Enter is to be handled as 1 number and then run the for loop once.


Change char c; to int c; as typically char encodes 256 different values and int getchar() returns 257 different values. @Jonathan Leffler