确保合法的字符输入

问题描述:一个良好的代码,在接受输入时,要确保输入的准确性,输入错误就要提示重新输入。这段代码就可以很好的解决这个问题。

此函数的主要功能是从给定字符串中选择一个字符。

int getlet(const char * s)
{
	char c;
	c = getchar();
	while (strchr(s, c) == NULL)
	{
		printf ("Enter a character in the list %s\n", s);
		while( getchar() != '\n')
			continue;
		c = getchar();
	}
	while (getchar() != '\n')
		continue;
	return c;
}

这个函数可以跟switch语句完美搭配,如以下模式:

#include <stdio.h>
int main(void)
{
	int choice;
	
    show_meau();
	while(choice == getlet("abcdq"))
	{
		if(choice == 'q') break;
		switch(choice)
		{
			case 'a':
				/*do something for input 'a'*/
			case 'b':
				/*do something for input 'b'*/
			case 'c':
				/*do something for input 'c'*/
			case 'd':
				/*do something for input 'd'*/
			default:
				printf("error!");/*This statement will never be executed. If it occurs, you win!*/
		}
	}
	
	return 0;
}

void show_meau(void)
{
	printf("input a ...\n");
	printf("input b ...\n");
	printf("input c ...\n");
	printf("input d ...\n");
	printf("input q means quit\n");
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值