学习

本文介绍了一个C语言程序,该程序通过getchar()和scanf()处理用户输入,确保只接收有效的字符和整数,并展示如何正确处理空格、制表符及换行符等特殊字符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
问题:while (getchar() != '\n')
			continue;   跳过一行的剩余字符

getchar()读取每个字符,包括空格,制表符和换行符,
scanf()在读取数字时,会跳过空格制表符,换行符。
时间:2016/4/16
*/
#include <stdio.h>
void display(char ch, int height, int width);
int get_int(void);

int main(void)
{
	int ch;
	int rows, cols;
	printf("enter a character and two integers:\n");
	while ((ch = getchar()) != '\n')
	{
		/*
		if (scanf_s("%d %d", &rows, &cols) != 2)   //输入错误类型,终止输入,退出
			break;*/

		rows=get_int();//给用户尝试输入正确类型的机会
		cols=get_int();
		if (rows < 0 || cols < 0)
		{
			printf("您输入的有不是正整数,请再次输入2个正整数:");
			rows = get_int();
			cols = get_int();
		}

		display(ch, rows, cols);
		while (getchar() != '\n')//scanf()函数将换行符留在了队列中。所以需要将换行符跳过,否则程序运行一次就结束。
			continue;
		printf("enter another character and two integers;\n");
		printf("enter a newline to quit.\n");
	}

	return 0;
}

void display(char ch, int height, int width)
{
	for (int row = 0; row < height; row++)
	{
		for (int col = 0; col < width; col++)
			putchar(ch);
		putchar('\n');
	}
}
/*
要求输入整型,给用户尝试输入正确类型的机会。
首先需要提出哪些有问题的输入;如果scanf()
没有输入成功,就会将其留在输入队列中。
可以使用getchar()逐个字符地读取,也可以如下做:
*/
int get_int(void)
{
	int input;
	char ch;
	while (scanf_s("%d", &input) != 1)
	{
		while ((ch = getchar()) != '\n')
			putchar(ch);//剔除错误输入
		printf("is not an integer,\n please enter an integer value, such as 1 ,-4 or 9: ");
	}

	return input;
}
</pre><pre code_snippet_id="1649962" snippet_file_name="blog_20160416_3_4937912" name="code" class="cpp">


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值