Mikayil Aliyev
Mikayil Aliyev

Reputation: 47

Problems with fgets function

Here I use fgets() to get user input with several strings, it never appeared in the output:

#include <stdio.h>

int main() {
    char color[20];
    char pluraNoun[20];
    char celebrity[20];

    printf("Enter a color: ");
    scanf("%s", color);
    printf("Enter a plural noun: ");
    scanf("%s", pluraNoun);
    printf("Enter a celebrity: ");

    fgets(celebrity, 20, stdin);

    printf("Roses are %s\n", color);
    printf("%s are blue\n", pluraNoun);
    printf("I love %s\n", celebrity);
    return 0;
}

Upvotes: 0

Views: 303

Answers (1)

user9706
user9706

Reputation:

Don't mix scanf() and fgets() or as man page says:

It is not advisable to mix calls to input functions from the stdio library with low-level calls to read(2) for the file descriptor associated with the input stream; the results will be undefined and very probably not what you want.

Here is a fgets() version:

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

#define LEN 20

char *strip(char *s) {
    size_t n = strlen(s);
    if(n && s[n-1] == '\n') s[n-1] = '\0';
    return s;
}

int main() {
    char color[LEN];
    char pluraNoun[LEN];
    char celebrity[LEN];

    printf("Enter a color: ");
    fgets(color, LEN, stdin);

    printf("Enter a plural noun: ");
    fgets(pluraNoun, LEN, stdin);

    printf("Enter a celebrity: ");
    fgets(celebrity, LEN, stdin);

    printf("Roses are %s\n", strip(color));
    printf("%s are blue\n", strip(pluraNoun));
    printf("I love %s\n", strip(celebrity));
    return 0;
}

You want check the return value from fgets() to ensure your program does something sensible on EOF.

Upvotes: 1

Related Questions