fgets 和 readRestOfLine 错误

fgets and readRestOfLine errors

我在使用 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] = '[=10=]';
    }


    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);
}

errors while creating a menu using fgets...

关于您的代码行:

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

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

Reads characters from the specified input stream into a lineBuffer until end-of-file is encountered, a newline character is read, or (number_ofChars - 1) characters are read. The newline character is retained. An ASCII NUL byte is appended to the end of the string. If successful, the function returns a pointer to 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 在语法上是正确的。