【问题标题】:How to terminate while loop using fscanf with stdin stream如何使用 fscanf 和 stdin 流终止 while 循环
【发布时间】:2016-06-30 08:37:15
【问题描述】:

我有点麻烦,我使用标准输入流使用 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' )

//所有运算符组合再次第四次

5)while( (fscanf(stdin,"%s",str) ) == 1 && str[0] != STOP )

//5 还有所有可能的运算符

我可以使用其他功能,我知道,但是我需要这个,因为首先是为了学习,因为我搜索过,但我没有找到任何东西,其次,我在以流为参数的函数中使用它,我正在根据我的需要更改该功能中的流,因为我必须使用此功能。

是的,如果有人想说详细一点,我希望我的 while 循环完全像这样 while 工作,

while( ( fgets(str,100,stdin) ) != NULL  && str[0] != '\n');

【问题讨论】:

  • 什么是input,它是如何填充的?
  • 你为什么不能用这个while循环和fgets
  • 输入只是书名。 @LPs
  • 因为我将这一行与两个流一起使用,例如如果文件打开,则获取文件指针,否则要求输入,以及我不想使用 fgets 的原因我的结构充满了指向 string 的指针,因此 fscanf 可以很好地处理这些文件条目。谢谢@GMichael
  • 输入中有空格吗?

标签: c arrays string loops


【解决方案1】:

如果您使用fscanf(stdin,"%s",str),则当用户按 Enter 时,您无法终止循环。这是因为%s 格式从输入流中读取下一个单词。当用户按 Enter 键时,它会继续从输入流中读取,直到找到一个单词。

您可以按照其他人的建议使用fgets。您可以逐个字符地读取输入并对其进行解析。您可能要求用户按 Ctrl-D(在 Unix 中)而不是 Enter,因为 Ctrl-D 报告 EOF。你甚至可以使用curses。用fscanf(stdin,"%s",str)回车,这个问题是无法解决的。

【讨论】:

    猜你喜欢
    • 2022-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多