栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C语言的循环语句中使用 scanf(“%c“,&x); 输入字符时的问题

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C语言的循环语句中使用 scanf(“%c“,&x); 输入字符时的问题

【示例代码】
下面代码,是在C语言的循环语句中使用 scanf("%c",&x); 输入字符,但输出的结果出乎意料。
原因详见问题分析。

#include 
#include 

char ch;
int n;

int main() {
	while(n<5) {
		printf("Please enter a letter: ");
		scanf("%c",&ch);
		printf("%cn",ch);
		
		n++;
	}

	return 0;
}


【问题分析】
本例代码执行后,会输出如下错误结果:即多了一条“Please enter a letter:”的提示。

Please enter a letter: M
M
Please enter a letter:

Please enter a letter:

原因在于,在C语言中,利用 scanf("%c",&x); 输入一个字符后的回车,会被作为字符存入缓冲区。
因此,第一次调用 scanf("%c",&x); 输入一个字符后的回车,被作为字符存入缓冲区。当下一次调用 scanf("%c",&x); 时,会从缓冲区取出回车符作为输入,这就在输入逻辑上造成了混乱。所以,就输出了出乎意料的结果。

【解决方法及正确代码】
将scanf("%c",&ch); 改为 scanf(" %c",&ch); 便可。即在%c前加一个空格。因为%c前面的空格,将清除缓冲区的内容。此外,getchar()函数也具有清除缓冲区的功能。所以,本例至少有两种解决方法。
方法一代码:

#include 
#include 

char ch;
int n;

int main() {
	while(n<5) {
		printf("Please enter a letter: ");		
		scanf(" %c",&ch);    //clear buffer and enter a letter			
		printf("%cn",ch);
		n++;
	}

	return 0;
}


方法二代码:

#include 
#include 

char ch;
int n;

int main() {
	while(n<5) {
		printf("Please enter a letter: ");		
		scanf("%c",&ch);				
		printf("%cn",ch);
		getchar();    //clear buffer
		n++;
	}

	return 0;
}




【参考文献】
https://blog.csdn.net/weixin_43260673/article/details/111460487
https://blog.csdn.net/qq_34316892/article/details/107459774

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/832563.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号