【问题标题】:fgets and readRestOfLine errorsfgets 和 readRestOfLine 错误
【发布时间】: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] 应该是 UB input[0] == '\0' - 但我怀疑这是有问题的。 2) readRestOfLine() 应在首次使用前声明/定义。
  • 始终为 EOF 测试 first
  • 代码在使用input之前应该检查fgets(input, 3, stdin);的返回值。

标签: c menu buffer fgets


【解决方案1】:

使用 fgets 创建菜单时出错...

关于你的代码行:

while ((c = fgets(stdin)) != '\n' && c != EOF);  

fgets,原型为:
char *fgets (char Line_Buffer[], int Number_of_Chars, FILE *Stream);

将指定输入流中的字符读取到 lineBuffer 中,直到遇到文件结尾、读取换行符或读取 (number_ofChars - 1) 个字符。换行符被保留。一个 ASCII NUL 字节被附加到字符串的末尾。如果成功,该函数返回一个指向 lineBuffer 的指针。

您只提供了 3 个必要参数中的 1 个。

使用示例

char buf[80];//line buffer with space for 80 char
int c;

while(fgets(buf, 80, stdin))
{ 
    //do something with buf
}  

另外,不要使用以下行:(未定义的行为)

if (input[strlen(input) - 1] != '\n')  //used twice in your code example

考虑像这样测试字符串的内容:

if(strstr(input, "\n"))//change the second argument to search for other values 
{
     //do something
}

请注意,您在发布的代码中首次使用 fgets 在语法上是正确的。

【讨论】:

  • fgets(stdin) 的成功之处。当然 OP 的编译器警告没有完全启用。
  • 是的,我想我应该指出这一点。但是你只有;)。顺便说一句,同样关于您对未定义行为的评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-03
相关资源
最近更新 更多