unable to use scanf twice for scanning a string and then scanning a char

被刻印的时光 ゝ 提交于 2019-12-24 15:15:13

问题


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;
}

another program which works

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

回答1:


Please add a space before %c in scanf().

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;
}


来源:https://stackoverflow.com/questions/26945123/unable-to-use-scanf-twice-for-scanning-a-string-and-then-scanning-a-char

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!