本文介绍了无法使用 scanf 两次扫描字符串然后扫描字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用 scanf
两次来扫描一个字符串,然后扫描一个字符.它首先扫描字符串并且不执行第二个scanf
.当我在一个 scanf
中同时使用 %s
和 %c
时,它工作得很好.你能告诉我为什么会这样吗?
I tried using scanf
twice for scanning a string and then scanning a char. It scans string first and does not execute the second scanf
. When I use both %s
and %c
in a single scanf
it works perfectly. Can you tell me why this happens?
#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()
中的%c
前加一个空格.
Please add a space before %c
in scanf()
.
在读取字符串后有一个换行符,所以这是由 %c
There is a newline character after the string is read so this is being taken by %c
#include<stdio.h>
int main()
{
char s[100],ch;
scanf("%s",s);
scanf(" %c",&ch);
printf("%s %c",s,ch);
return 0;
}
这篇关于无法使用 scanf 两次扫描字符串然后扫描字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!