linux程序设计 第4版 第145页 有一个菜单例程,程序如下
#include<stdio.h>
#include<stdlib.h>
char *menu[]={"a - add new record",
"d - delete record",
"q - quit",
NULL,
};
int getchoice(char *greet, char *choices[])
{
int chosen = 0;
int selected;
char **option;
do{
printf("Choice: %s\n", greet);
option = choices;
while (*option)
{
printf("%s\n", *option);
option++;
}
selected = getchar();
option = choices;
while (*option)
{
if (selected == *option[0])
{ chosen = 1; break;}
option++;
}
if (!chosen)
printf("Incorrect choice, select again\n");
}while(!chosen);
return selected;
}
int main()
{
int choice = 0;
do
{
choice = getchoice("Please select an action", menu);
printf("You have chosen: %c\n", choice);
}while(choice != 'q');
exit(0);
}
运行如下:
Choice: Please select an action
a - add new record

在Linux程序设计中,遇到getchar()函数因回车导致的错误。当输入字符后,回车会被getchar()接收,造成错误的连续执行。解决方法是在读取字符后,额外接收并忽略回车。通过修改代码,确保getchar()只处理用户期望的输入,避免缓冲区中遗留的回车影响程序流程。一次输入多个字符,getchar()会依次处理,直至缓冲区清空。
最低0.47元/天 解锁文章
646

被折叠的 条评论
为什么被折叠?



