getchar()和scanf()用法

本文详细讲解了getchar()和scanf()的基本用法,包括它们的MSDN定义、输入场景及常见问题。通过实例演示了如何避免缓冲区读取误差,并提供了两种改进方法:连续读取和处理空格后的输入。最后介绍了scanf()的返回值机制,以及如何利用~scanf()实现连续读取。
摘要由CSDN通过智能技术生成

getchar()和scanf()用法

一些定义

根据MSDN对getchar()的定义:

int getchar(void);
Each of these functions returns the character read. To indicate an read error or end-of-file condition, get and getchar return EOF, and getwc and getwchar return WEOF, for getc and getchar, use ferror or feof to chheck for an error or for end of file.

以及对scanf()的定义

int scanf();
Both scanf and wscanf return the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned. The return value is EOF for an error or if the end-of-file character or the end-of-string character is encountered in the first attempt to read a character.

scanf()输入成功时返回输入成功赋值的数据项数,失败则返回EOF。
EOF: End-Of-File 文件结束标志,本质上是-1。

使用场景

问题代码

	char password[20] = { 0 };
	printf("Input password:>");
	scanf("%s", password);
	
	printf("Confirm(Y/N):>");
	int ch = getchar();
	if ('Y' == ch)
		printf("Confirm successfully");
	else
		printf("Cancceled");

运行结果:在这里插入图片描述

原因

scanf()和getchar()是从缓冲区中读取数据的。当输入"123456\n"时,scanf()会把\123456读走,当按下回车键(即\n)时,getchar()从缓冲区中将\n读走,因此确认失败。

修正

方法一:

	...
	getchar();

	printf("Confirm(Y/N):>");
	int ch = getchar();
	if ('Y' == ch)
		printf("Confirm successfully");
	else
		printf("Cancceled");

这种方法有缺陷,如果输入"123456 abcdef\n"仍然会读取失败。scanf(“%s”)只会读取空格之前的字符串即"123456 “。getchar()只能处理接下来的"a”。

方法二:

	int tmp = 0;
	while ((tmp = getchar()) != '\n')
	{
		;
	}

	printf("Confirm(Y/N):>");
	int ch = getchar();
	if ('Y' == ch)
		printf("Confirm successfully");
	else
		printf("Cancceled");

使用

连续读取:

	while ((ch = getchar()) != EOF)
	{
		putchar(ch);
	}

读取带空格的字符串等:

	while ((tmp = getchar()) != '\n')
	{
		;
	}
	写法一:
	while (EOF != scanf("%s", ch))
	{
	
	}
	
	写法二:
	while (~scanf("%s", ch))

scanf()每次只读取空格前的内容,空格后的内容放在缓冲区中留待下次循环读取,因此可以实现连续读取。

这两种写法是一样的。scanf()输入错误返回的是-1。~scanf()指的就是当scanf()读到-1时,将-1按位取反,计算机中存储的是补码,即 ~11111111=00000000,此时while的判断条件为假跳出循环。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Weijian Feng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值