質問

To read multi-word strings, I have been using the gets() function. The behaviour of the gets() function is unpredictable to me and I use the statement fflush(stdin) before every gets() statement to avoid issues. Is using this statement this way appropriate? What can be an alternative approach?

役に立ちましたか?

解決 2

You can use fgets() instead of gets(): https://stackoverflow.com/a/4309760/1758762

As everyone else said, the canonical alternative to gets() is fgets() specifying stdin as the file stream.

char buffer[BUFSIZ];

while (fgets(buffer, sizeof(buffer), stdin) != 0)
{
    ...process line of data...
}

What no-one else yet mentioned is that gets() does not include the newline but fgets() does. So, you might need to use a wrapper around fgets() that deletes the newline:

char *fgets_wrapper(char *buffer, size_t buflen, FILE *fp)
{
    if (fgets(buffer, buflen, fp) != 0)
    {
        size_t len = strlen(buffer);
        if (len > 0 && buffer[len-1] == '\n')
            buffer[len-1] = '\0';
        return buffer;
    }
    return 0;
}

他のヒント

fflush only flush output streams.

If you want to flush stdin, keep reading until you get EOF, something like:

int i;
while (((i = getchar()) != '\n') && (i != EOF));

You can use a scanf statement with appropriate Regular expression.

scanf("%[^\n]s",str);


or maybe a fgets statement.

fgets(str, sizeof(str),stdin));

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top