与fgets不scanf的工作后, [英] fgets doesn't work after scanf

查看:135
本文介绍了与fgets不scanf的工作后,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我进入循环后,S1被自动分配一个空行。它是如何发生的?我敢肯定,我的键盘工作正常。

After I entered "loops", "s1" was assigned a blank line automatically. How does it happen? I'm sure my keyboard works fine.

推荐答案

scanf()的读什么你问它,留下以下 \\ n 从缓冲区行的末尾,其中与fgets()阅读。要么做一些消耗换行符,或(我的preferred溶液)与fgets()然后的sscanf()从该字符串。

scanf() reads exactly what you asked it to, leaving the following \n from the end of that line in the buffer where fgets() will read it. Either do something to consume the newline, or (my preferred solution) fgets() and then sscanf() from that string.

这篇关于与fgets不scanf的工作后,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆