【发布时间】:2015-08-26 15:10:49
【问题描述】:
我在使用 fgets 和 readrestofline 函数创建菜单时出错。我不知道错误来自哪里。我错过了什么吗?编译后,“fgets”、“readrestofline”和“stdin”处显示错误。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int printMenu(void)
{
int option;
char input[3];
while((option != 3)||(option < 4)||(option > 0))
{
printf("Welcome\n");
printf("---------------------\n");
printf("1.Play \n2.Display Scores\n3.Quit\n");
printf("Please enter your choice: ");
fgets(input, 3, stdin);
if (input[strlen(input) - 1] != '\n')
{
printf("Input was too long.\n");
readRestOfLine();
}
else
{
input[strlen(input) - 1] = '\0';
}
switch (option)
{
case 1:
printf("Loading ...\n");
break;
case 2:
printf("Loading ...\n");
break;
case 3:
printf("Quitting...\n");
exit(0);
break;
default:
printf("Invalid ! Please choose again.\n");
break;
}
}
}
void readRestOfLine()
{
int c;
/*read until the end of the line or end-of-file*/
while ((c = fgets(stdin)) != '\n' && c != EOF);
/*clear the error and end-of-file flags*/
clearerr(stdin);
}
【问题讨论】:
-
1)
input[strlen(input) - 1]应该是 UBinput[0] == '\0'- 但我怀疑这是有问题的。 2)readRestOfLine()应在首次使用前声明/定义。 -
始终为 EOF 测试 first。
-
代码在使用
input之前应该检查fgets(input, 3, stdin);的返回值。