无法使用 scanf 两次扫描字符串然后扫描字符 [英] unable to use scanf twice for scanning a string and then scanning a char

查看:44
本文介绍了无法使用 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 两次扫描字符串然后扫描字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆