scanf 后 fgets 不起作用 [英] fgets doesn't work after scanf

查看:34
本文介绍了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)] = '';
        s2[strlen(s2)] = '';

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

        delspace(s1);
        delspace(s2);

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

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

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

    return 0;
}

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

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

在我输入loops"后,s1"被自动分配了一个空行.它是如何发生的?我确定我的键盘工作正常.

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

推荐答案

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

scanf() reads exactly what you asked it to, leaving the following 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.

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

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