我的控制台应用程序中有这个循环:
do{
printf("\n %sVotre choix :%s ",GREEN_BOLD,RESETCOLOR);
choix = tolower(getchar());
}while((choix != 'c') && (choix != 'l') && (choix != 'e') && (choix != 's'));
因此,当用户键入的字符不是 c
、l
、e
或 s
之一时>,他将再次收到消息 Votre choix :
并且程序等待他输入其他字符,但问题是用户收到该消息两次,我认为这是因为当用户键入时一些字符,然后他点击 Return
,在下一次 Return
迭代中,它将被读取为一个字符,这是我得到的截图:
如何阻止我的应用程序将 Return
作为字符读取?
最佳答案
使用 "%c"
首先消耗之前的空格,包括一个“Return”,然后读取 1 个 char
。
char choix = 0;
do {
printf("\n %sVotre choix :%s ",GREEN_BOLD,RESETCOLOR);
// choix = tolower(getchar());
scanf(" %c", &choix);
choix = tolower(choix);
} while((choix != 'c') && (choix != 'l') && (choix != 'e') && (choix != 's'));
更好的方法是使用 fgets() sscanf()
团队。
char choix;
do {
printf("\n %sVotre choix :%s ",GREEN_BOLD,RESETCOLOR);
char buf[10];
if (fgets(buf, sizeof buf, stdin) == NULL) break; // EOF or I/O error
if (sscanf(buf, " %c", &choix) != 1) continue;
choix = tolower(choix);
} while((choix != 'c') && (choix != 'l') && (choix != 'e') && (choix != 's'));
关于c - 避免我的应用程序将 Return 读取为字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19393281/