【发布时间】:2018-04-14 10:24:54
【问题描述】:
我有一个小程序,我想询问一个选项,然后询问一个文件名。
//Some code before
printf("######################\n");
printf("# 1. Register a file #\n");
printf("# 2. Get global list #\n");
printf("# 3. Download a file #\n");
printf("# 4. Quit / Exit #\n");
printf("######################\n");
printf("Enter decision: ");
fflush(stdin);
action = getchar();
action -= '0';
sprintf(input, "[%d]--", action);
switch (action)
{
case 1:
printf("Enter file name: ");
fflush(stdin);
fgets(input+strlen(input), LINE_LEN, stdin);
input[strlen(input)] = (input[strlen(input)] == '\n') ? 0 : input[strlen(input)];
if(write(sock, input, sizeof(input)) == -1) perror("Clienthandler Write 3");
break;
//some code after
问题是我的 fget 被跳过了,即使在 gdb 中,gdb 在 inspect input 的 fgets 之后显示 "\n\000]--" action = 1 时的值
这是控制台输出:
######################
# 1. Register a file #
# 2. Get global list #
# 3. Download a file #
# 4. Quit / Exit #
######################
Enter decision: 1
Enter file name: ######################
# 1. Register a file #
# 2. Get global list #
# 3. Download a file #
# 4. Quit / Exit #
######################
Enter decision: ^C
【问题讨论】:
-
fflush(stdin);不起作用。使用__fpurge(stdin),但应避免使用。 -
而不是调用
strlen(input)3次,只需将结果存储在一个变量中并重复使用它[ -
@achal:
__fpurge()来自哪里? -
@alk OP 说 我的 fgets 被跳过了 ?可能是什么原因?当然
stdin不清楚,用户需要冲洗它。fflush(stdin)不起作用,因为它用于输出流。其他选项是 OP 应该使用\n或__fpurge(stdin)。我同意__fpurge(stdin)不可移植,直到 glibc 2.1.95 -
@achal:如果你愿意,请看我的回答。