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?
Asked
Active
Viewed 167 times
3

amulous
- 704
- 2
- 6
- 15
3 Answers
3
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));

Guillaume
- 10,463
- 1
- 33
- 47
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;
}

Community
- 1
- 1

Leo Chapiro
- 13,678
- 8
- 61
- 92
-
Thanks! But if BUFSIZ is not known beforehand and I create a string using a char pointer, how can fgets() be used? – amulous Jun 24 '13 at 10:32
-
BUFSIZ is just a constant to be define like #define BUFSIZ 255 or something else ... – Leo Chapiro Jun 24 '13 at 10:33
1
You can use a scanf statement with appropriate Regular expression.
scanf("%[^\n]s",str);
or maybe a fgets statement.fgets(str, sizeof(str),stdin));

nj-ath
- 3,028
- 2
- 25
- 41