C,冲洗标准输入 [英] C, flushing stdin
问题描述
我有使用与fgets的问题。循环应该读取一行最大的。 19个字符,分析这个字符数组,然后等待下一个输入。
问题是,如果线路输入exeeds 19个字符,与fgets将填补海峡与剩余的字符,直到按下Ctrl-D或换行输入,从而启动无新输入一个新的循环。输入(标准输入)应19个字符被读取后,以某种方式被刷新,所以循环可以改过自新。任何人有一个解决的办法?
字符海峡[20];
而((与fgets(STR,20,标准输入)!= NULL)){
看跌期权(STR); //监控海峡 如果(STR [0] =='Q')破;
}
实例使用:
HOLA特力屋//用户输入9字符+换行
HOLA特力屋//把写入胡胡胡胡HOOH //用户输入20个字符+换行
呼胡胡胡胡//把写入
H //
scanf函数(%* [^ \\ n] \\ n);
可能是一简单的准备。
i have a problem with the use of fgets. The loop is supposed to read a line of max. 19 characters, analyze this char array and then wait for next input. The problem is that if the line entered exeeds 19 characters, fgets will fill str with the remaining characters untill Ctrl-D or newline is entered, thus initiating a new loop without new input. The input (stdin) should in some way be flushed after 19 characters are read, so the loop can start with a clean slate. Anyone have a solution to this?
char str[20];
while((fgets(str, 20, stdin) != NULL)) {
puts(str); //monitoring str
if(str[0] == 'q') break;
}
Example in use:
hola hola //user inputs 9 chars + newline
hola hola //puts writes
hoo hoo hoo hoo hooh //user inputs 20 chars + newline
hoo hoo hoo hoo hoo //puts writes
h //
scanf("%*[^\n]\n");
is probably one of the simplest possibilities.
这篇关于C,冲洗标准输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!