Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fgets doesn't work after scanf [duplicate]

Tags:

c

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

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

like image 440
Vayn Avatar asked May 06 '11 23:05

Vayn


People also ask

How do I use fgets after scanf?

How do I make Fgets work after scanf? This can be solved by introducing a “\n” in scanf() as in scanf(“%d\n”, &x) or by adding getchar() after scanf().

Why is my fgets not working in C?

fgets() is a file function used to read (or get) string from a file. As strong is not a built in data type in C language or as C doesn't support string data type fgets() is not working in C.

What is the problem of using scanf () function?

Explanation: The problem with the above code is scanf() reads an integer and leaves a newline character in the buffer. So fgets() only reads newline and the string “test” is ignored by the program. 2) The similar problem occurs when scanf() is used in a loop.

Does fgets wait for input?

fgets doesnt wait for input, enters blank line (cant find a way to remove trailing newline char) thats one possible solution, run that between each makeItem call.


1 Answers

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.

like image 53
geekosaur Avatar answered Oct 22 '22 23:10

geekosaur