Mickey
Mickey

Reputation: 1525

Reading character by character from stdin until EOF in C

I'm trying to read a string in C until EOF, but react to every character before the input of the next character. For example: A user inputs abcd, and right after every character input, I will do some calculations on each character. I have tried to approach this in two different ways:

Option 1, using getchar():

int d;
char c;

while ((d = getchar()) != EOF) {
    c = (char)d;
    <<< DO SOME CALCULATIONS ON 'c'>>>
    }

Option 2, using scanf:

char c;
while (scanf(" %c",&c) != EOF) {
    <<< DO SOME CALCULATIONS ON 'c'>>>
}

However, both approaches seem to fail. It seems that the getchar() and scanf() gets all the characters until it encounters the 'EOF', and only then enters the while loop.

Would love some help on this, Thanks!

Upvotes: 2

Views: 3654

Answers (1)

Chandanard
Chandanard

Reputation: 1

scanf manual says :

"The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error."

.. better use a do..while approch with scanf in this case (and if you want store return of scanf to check for errors) :

char c;

do{
  scanf("%c",&c);
  /* DO SOME CALCULATIONS ON 'c' */
}while(c != EOF);

same with getchar() in raw mode will react to each user keystroke

see this for using raw mode : https://stackoverflow.com/a/22517349/8907248

Upvotes: -2

Related Questions