简体   繁体   English

从stdin到C中的EOF逐字符读取

[英]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. 我试图在C中读取一个字符串,直到EOF,但对输入下一个字符之前的每个字符做出反应。 For example: A user inputs abcd , and right after every character input, I will do some calculations on each character. 例如:用户输入abcd ,并且在每个字符输入之后,我都会对每个字符进行一些计算。 I have tried to approach this in two different ways: 我试图用两种不同的方法来解决这个问题:

Option 1, using getchar(): 选项1,使用getchar():

int d;
char c;

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

Option 2, using scanf: 选项2,使用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. 似乎getchar()和scanf()会获取所有字符,直到遇到'EOF',然后才进入while循环。

Would love some help on this, Thanks! 希望对此有所帮助,谢谢!

scanf manual says : scanf手册说:

"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." “如果在第一次成功转换或匹配失败之前输入结束,则返回EOF值。如果发生读取错误,也会返回EOF,在这种情况下,流的错误指示符(请参见ferror(3)设置为,而errno设置为错误。”

.. better use a do..while approch with scanf in this case (and if you want store return of scanf to check for errors) : ..在这种情况下,最好使用do..while与scanf配合使用(如果要存储scanf的返回值以检查错误):

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 与原始模式下的getchar()相同,将对每个用户击键做出反应

see this for using raw mode : https://stackoverflow.com/a/22517349/8907248 看到使用原始模式的情况: https : //stackoverflow.com/a/22517349/8907248

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM