【问题标题】:unable to use scanf twice for scanning a string and then scanning a char无法使用 scanf 两次扫描字符串然后扫描字符
【发布时间】:2014-11-15 11:03:18
【问题描述】:

我尝试使用scanf 两次扫描字符串,然后扫描字符。它首先扫描字符串并且不执行第二个scanf。当我在一个scanf 中同时使用%s%c 时,它可以完美运行。你能告诉我为什么会这样吗?

#include<stdio.h>
int main()
{
char s[100],ch;
scanf("%s",s);
scanf("%c",&ch);   //this does not work
printf("%s %c",s,ch);
return 0;
}

另一个有效的程序

#include<stdio.h>
int main()
{
char s[100],ch;
scanf("%s %c",s,&ch);  //this works!
printf("%s %c",s,ch);
return 0;
}

【问题讨论】:

  • “不起作用”并没有向我们解释发生了什么。你期望会发生什么?究竟发生了什么?你做了什么来尝试理解问题?当您在程序中使用调试器时发生了什么?
  • 在第一个选项中,在第二个scanf之后立即放置一个断点并检查ch的值。很可能是第一个 scanf 中的换行符。不要吝啬学习如何调试你的代码,它会在未来帮助你。
  • 注意:避免裸体"%s"。最好在这里使用"%99s"

标签: c stdin scanf


【解决方案1】:

请在scanf() 中的%c 之前添加一个空格。

读取字符串后有一个换行符,因此%c正在使用该字符

#include<stdio.h>
int main()
{
char s[100],ch;
scanf("%s",s);
scanf(" %c",&ch);   
printf("%s %c",s,ch);
return 0;
}

【讨论】:

  • 从 scanf 清除剩余换行符的另一种逻辑上更明显 (IMO) 的方法是在输入的格式化程序之后添加 %*c ——所以你可以在上面的片段中使用 scanf ("%s%*c", s); ;这会清除缓冲区,因此下一个 scanf 调用不会读取前一个在缓冲区中留下的换行符。格式条目中 % 后的 * 告诉 scanf 丢弃扫描的值(对于任何格式)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多