我有点麻烦,我正在使用标准输入流使用 fscanf() 库函数从键盘请求输入。
#define STOP '.'
char str[100]; //string variable
while( (fscanf(stdin,"%s",str) ) == 1) {
//code
//code
}
//如果用户按下回车,我想终止这个循环,我已经尝试过的是:
1)while( (fscanf(stdin,"%s",str) ) > 0 )
2)while( (fscanf(stdin,"%s",str) ) < 0 )
3)while( (fscanf(stdin,"%s",str) ) == 1 && str[0] != '\n' )
//第三个运算符的所有组合
4)while( (fscanf(stdin,"%s",str) ) == 1 && str[0] != '\0' )
//再次与所有运算符组合第 4
5)while( (fscanf(stdin,"%s",str) ) == 1 && str[0] != STOP )
//5 还有所有可能的运算符
我可以使用其他函数,我知道,但我需要这个,因为首先是为了学习,当我搜索时我没有找到任何东西,其次,我在将流作为参数的函数中使用它并且我正在根据我的需要更改该函数中的流,为此我必须使用该函数。
是的,如果有人想详细说明,我希望我的 while 循环完全像这样工作,
while( ( fgets(str,100,stdin) ) != NULL && str[0] != '\n');
最佳答案
如果使用 fscanf(stdin,"%s",str)
,则无法在用户按下 Enter 时终止循环。这是因为 %s
格式从输入流中读取下一个单词。当用户按下 Enter 键时,它会继续从输入流中读取,直到找到一个单词。
您可以按照其他人的建议使用fgets
。您可以逐字符读取输入并解析它。您可能需要用户按 Ctrl-D(在 Unix 中)而不是 Enter,因为 Ctrl-D 报告 EOF。您甚至可以使用 curses
。用fscanf(stdin,"%s",str)
回车,问题无解。
关于c - 如何使用带有标准输入流的 fscanf 终止 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38117928/