在scanf之后fgets不起作用

Vay*_*ayn 11 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);
}
Run Code Online (Sandbox Code Playgroud)

输入"循环"后,"s1"自动分配一个空行.怎么会发生?我确定我的键盘工作正常.

gee*_*aur 18

scanf()准确读出你要求它的内容,\n从缓冲区中该行的末尾留下以下内容fgets()将读取它.要么做一些事情来消费新行,或者(我的首选解决方案)fgets(),然后sscanf()从该字符串.

  • 在格式的末尾使用类似'%*[^ \n]%*c`的内容来跳过换行符中的任何字符,然后是换行符本身. (5认同)
  • @geekosaur:如果在上一个事物读取之后和换行符之前没有字符,那么只要将'%*[^ \n]%*c`添加到格式的末尾就不会真正起作用,因为`%*[^ \n]`将无法匹配,因此将跳过`%*c`并且新行仍将保留在输入上.您需要在单独的scanf调用中执行`%*c`才能使其正常工作. (2认同)

Shu*_*war 6

这是一个更简单的解决方案

scanf("%d",&loops);
while ((getchar()) != '\n'); //This will consume the '\n' char
//now you're free to use fgets
fgets(string,sizeof(string),stdin);
Run Code Online (Sandbox Code Playgroud)


hug*_*omg 5

scanf在输入缓冲区中留下空格,包括换行符.要使用fgets读取下一行,您需要手动删除当前行的其余部分:

int c;
do{
    c = getchar();
}while(c != EOF && c != '\n');
Run Code Online (Sandbox Code Playgroud)