c - scanf 之后 fgets 不起作用

标签 c scanf fgets

#include <stdio.h>
#include <string.h>
#include <ctype.h>

void delspace(char *str);

int main() {
    int i, loops;
    char s1[101], s2[101];

    scanf("%d", &loops);

    while (loops--) {
        fgets(s1, 101, stdin);
        fgets(s2, 101, stdin);
        s1[strlen(s1)] = '\0';
        s2[strlen(s2)] = '\0';

        if (s1[0] == '\n' && s2[0] == '\n') {
            printf("YES\n");
            continue;
        }

        delspace(s1);
        delspace(s2);

        for (i = 0; s1[i] != '\0'; i++)
            s1[i] = tolower(s1[i]);

        for (i = 0; s2[i] != '\0'; i++)
            s2[i] = tolower(s2[i]);

        if (strcmp(s1, s2) == 0) {
            printf("YES\n");
        }
        else {
            printf("NO\n");
        }
    }

    return 0;
}

void delspace(char* str) {
    int i = 0;
    int j = 0;
    char sTmp[strlen(str)];

    while (str[i++] != '\0') {
        if (str[i] != ' ') {
            sTmp[j++] = str[i];
        }
    }
    sTmp[j] = '\0';
    strcpy(str, sTmp);
}

输入“loops”后,“s1”会自动分配一个空行。这是怎么发生的?我确信我的键盘工作正常。

最佳答案

scanf() 准确读取您要求的内容,并在缓冲区中的该行末尾留下以下 \n,其中 fgets() 将读取它。要么做一些事情来消耗换行符,要么(我的首选解决方案)fgets(),然后从该字符串中sscanf()

关于c - scanf 之后 fgets 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55713670/

相关文章:

c - 每 x 分钟更新一次变量

c - fscanf 没有读取文件中的 double 值。文件没问题

c - 如何在 C 中计算整数数组元素(例如基于 char 的 strlen())?

c - 在C中扫描并打印变量数据类型 "double"

c - malloc + fgets 动态分配

c++ - 将 C++ 方法和变量并排绑定(bind)到一个表

C 值数组,指针段错误

c - 使用 GPROF 自动分析 C 程序

c - 读取数百行后程序中断

c - 使用 gets() 进行缓冲存储