360NS
360NS

Reputation: 176

printing stdin char by char until end of file

we were asked to make a small program that would print each char from stdin using getchar()... I thought the following code would work but when i run it in windows console nothing happens, the cursor hangs indefinitely as if it's waiting for input...

int c = 0;
while(c != EOF)
{
    c = getchar();
    printf("%c\n", c);
}
printf("\nOut of loop!\n");

i thought the code would print the stream char by char, and if there was nothing in stdin, getchar() would return EOF and the loop would stop.. i think i'm misunderstanding something about how input is done in C, for a beginner it's really confusing... Any help!


Another confusing example:

char str[100]={0};
printf("Entrer a string: ");
scanf("%s",str); //i'll enter a string with spaces to have something to print in the loop
//let's say i enter Hello Wor^Zld!
int c = 0;
while(c!=EOF)
{
    c = getchar();
    printf("%c",c);
}
printf("Finally done with loop!!\n");


when i run the above code i get the following display in the console:
Wor->
with the same old cursor hanging waiting for input... Any idea why is that? it seems that Ctrl-Z+Enter "^Z-Enter" stopped the display but the loop continues? i'm honestly doing my best to understand but i got to be honest it's confusing.. Thank you in advance for helping and bearing with me!

Upvotes: 0

Views: 2400

Answers (1)

Stargateur
Stargateur

Reputation: 26767

You should fflush your output if you want be sure that it's print when you want. You should test EOF before try to print your character.

int c;
while((c = getchar()) != EOF)
{
    printf("%c\n", (char)c);
    fflush(stdout);
}
printf("Out of loop!\n");

Upvotes: 0

Related Questions