Rick
Rick

Reputation: 7506

ch2=getchar() doesn't work after last input loop while((ch=getchar())!=EOF)

#include <stdio.h>
int main(){
    char ch;
    while((ch=getchar())!=EOF){
       putchar(ch);
    }
    char ch2 = 'A';
    printf("ch2=======>%c\n",ch2);
    ch2 = getchar();
    printf("ch2=======>%d\n",ch2);
    return 0;
}

I don't understand why it skips the ch2=getchar() input, and I get ch2 == -1 which is the value of EOF. I tried to solve this by adding another getchar() before ch2=getchar(), but I still get ch2 == -1. Why is it and how to fix it? Thanks for helping.

I'm using MacOS.

Upvotes: 2

Views: 256

Answers (2)

user3629249
user3629249

Reputation: 16540

When compiling, always enable all the warnings, then fix those warnings

I used this version of your code, which cleanly compiles:

#include <stdio.h>
int main(){
    int ch;
    while((ch=getchar())!=EOF){
       putchar(ch);
    }
    int ch2 = 'A';
    printf("ch2=======>%c\n",ch2);
    ch2 = getchar();
    printf("ch2=======>%d\n",ch2);
    return 0;
}

then entered:

ddd<ctrl-d>ccc<cr>

this is the expected (and actual) result:

ddd
ddd
ch2=======>A
ccc
ch2=======>99

Notes:

1) getchar() does not return until a <cr> or <ctrl-d> is entered

2) all entered characters are echo'd by the terminal driver (not the program)

3) there are still 2 cs and a <cr> in the input buffer that have not been consumed

Upvotes: 1

Sergio
Sergio

Reputation: 8209

There is nothing surprising. Your loop

while((ch=getchar())!=EOF){
       putchar(ch);
}

exhausts stdin completely. Then printf() adds some data to stdout, but stdin is still empty, so subsequent getchar() returns EOF.

Upvotes: 0

Related Questions