【问题标题】:How can i get string using scanf as i want it to be?如何使用我想要的 scanf 获取字符串?
【发布时间】:2018-11-30 12:52:28
【问题描述】:

如何使用 scanf 读取带空格的字符串(无需回车)?而且我还希望这个程序在输入为 EOF 时停止

我使用了以下代码:

int main()      //this is not the whole program
{
    char A[10000];
    int length;

    while(scanf(" %[^\n]s",A)!=EOF);
    {
        length=strlen(A);
        print(length,A); 
        //printf("HELLO\n");
    }


    return 0;
}

但它正在读取两个 EOF(ctrl+Z) 来停止程序。有人能给我任何建议吗?

【问题讨论】:

  • "%[" 格式开始,以"]" 结尾。您拥有的 "s" 不是格式说明符的一部分,scanf 函数希望显式匹配它。此外,scanf 仅在存在错误或实际文件结尾时才返回 EOF,而不是在格式不匹配时返回。
  • 哦,我可能应该从以下开始:如何“表现得很奇怪”?对于某些指定的输入,它的预期行为和输出是什么?什么是实际行为和输出?另请阅读how to ask good questionsthis question checklist。最后学习如何创建minimal reproducible example
  • 正在读取两个EOF(ctrl+Z)来停止程序
  • 不要使用scanf!

标签: c string scanf


【解决方案1】:

它正在读取两个EOF(ctrl+Z)来停止程序

没有。您可能按了两次^Z,但scanf() 只是“读取”一个文件结尾EOF。这就是您的键盘/操作系统界面的工作方式。研究如何发出文件结束信号。

其他变化

char A[10000];
// while(scanf(" %[^\n]s",A)!=EOF);
// Drop final `;`  (That ends the while block)
// Add width limit
// Compare against the desired result, 1, not against one of the undesired results, EOF
// Drop the 's'
while(scanf(" %9999[^\n]", A) == 1) {
    length=strlen(A);
    // print(length,A); 
    print("%d <%s>\n", length, A); 
    //printf("HELLO\n");
}

【讨论】:

  • 感谢您的建议。 您能解释一下“scanf(" %9999[^\n]", A) == 1)" 吗?我是 c 编程新手。可能会有所帮助
  • @mahinhossen 查看C library function - scanf()Scansets in C 并告诉我还有什么需要解释的。
猜你喜欢
  • 2020-12-19
  • 2017-07-25
  • 2014-09-01
  • 1970-01-01
  • 2017-04-03
  • 1970-01-01
  • 2021-02-27
  • 2018-05-06
  • 1970-01-01
相关资源
最近更新 更多