[fgets和sscanf在c中被跳过?

问题描述 投票:-1回答:1

在我的代码中,我确保用户输入以下缩写类之一,但是我的fgets导致很多逻辑错误。

char class[3];
char arr3[5];
i = 0;
    while(i == 0){
        printf("Enter the class, either FR, SO, JR, SR, GR, RFR, or RSO\n");
        fgets(arr3, sizeof(arr3), stdin);

        if(sscanf(arr3, "%s", class) == 1){

            if(strcmp(class, "FR\0") == 1 || strcmp(class, "SO\0") == 1)
                i = 1;
            else if(strcmp(class, "JR\0") == 1 || strcmp(class, "SR\0") == 1)
                i = 1;
            else if(strcmp(class, "GR\0") == 1 || strcmp(class, "RFR\0") == 1)
                i = 1;
            else if(strcmp(class, "RSO\0") == 1)
                i = 1;
            else
                printf("Enter one of the classes.  Must be all caps.\n");
        }
        else if(sscanf(arr3, "%s", class) != 1)
            printf("An error has occured.\n");
    }

当我运行代码时,发生的第一件事是它跳过了fget,然后打印:输入其中一个类别。必须全部大写。这是否意味着它已读入标准输入中的某些内容?

c scanf fgets
1个回答
0
投票

根据我的评论,您有很多错误,但是最大的问题是[[不要对缓冲区大小无视!。您的下一个困惑点是,当字符串匹配时,strcmp返回零,而不是1。不要尝试通过截断将'\n'包含的尾随fgets删除到较短的数组,只需使用strcspn删除它即可。

A

String Literal

提供nul-termianting字符,因此"\0"中的"SR\0"是多余的。摆脱它们。进行这些更改,您可以执行:

#include <stdio.h> #include <string.h> #define BUFC 1024 /* if you need a constant, #define one (or more) */ int main (void) { char buf[BUFC]; int i = 0; while (i == 0) { printf("Enter the class, either FR, SO, JR, SR, GR, RFR, or RSO\n"); if (!fgets (buf, BUFC, stdin)) { fputs ("(user canceled input)\n", stdout); return 1; } buf[strcspn (buf, "\n")] = 0; /* trim newline from buf */ /* strcmp equality return is 0 */ if (strcmp (buf, "FR") == 0 || strcmp (buf, "SO") == 0 || strcmp (buf, "JR") == 0 || strcmp (buf, "SR") == 0 || strcmp (buf, "GR") == 0 || strcmp (buf, "RFR") == 0 || strcmp (buf, "RSO") == 0) i = 1; else printf("Enter one of the classes. Must be all caps.\n"); } printf ("\nclass: %s\n", buf); }

示例使用/输出

$ ./bin/enterclasses Enter the class, either FR, SO, JR, SR, GR, RFR, or RSO banannas Enter one of the classes. Must be all caps. Enter the class, either FR, SO, JR, SR, GR, RFR, or RSO NO Enter one of the classes. Must be all caps. Enter the class, either FR, SO, JR, SR, GR, RFR, or RSO RFR class: RFR
仔细检查,如果还有其他问题,请告诉我。
© www.soinside.com 2019 - 2024. All rights reserved.