问题描述:一个良好的代码,在接受输入时,要确保输入的准确性,输入错误就要提示重新输入。这段代码就可以很好的解决这个问题。
此函数的主要功能是从给定字符串中选择一个字符。
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");
}