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.
Because OP pressed 2 keys: 6 and Enter before signaling end-of-file.
The
forloop ran once for each character:'6'and'\n'.It appears OP wants to run the loop per each digit.
Amend code to only run the loop when the key is a digit:
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
forloop once.Change
char c;toint c;as typicallycharencodes 256 different values andint getchar()returns 257 different values. @Jonathan Leffler