Reputation: 33
I have two inputs using fgets() function. Obviously, I declare size of input hoping it will truncate the input. It does truncate the input, but the remaining characters overflow into the following fgets(). I thought flushing the stdin would be the fix, but it doesn't seem to be working. Any help? Example below.
char a[3];
char b[3];
fgets(a, sizeof(a), stdin);
fflush(stdin);
fgets(b, sizeof(b), stdin);
fprintf(stderr, "%s%s", a, b);
an input of "help" followed by "ok" would produce the following:
hel
pok
Upvotes: 0
Views: 574
Reputation: 16540
how to flush stdin
Do NOT use: fflush( stdin )
The function: fflush()
is ONLY for output streams and the C programming language specifically states that calling fflush()
with an input stream results in undefined behavior. (regardless of what visual studio might allow)
Suggest:
int ch;
while( (ch = getchar() ) != EOF && ch != '\n' ){;}
regarding the function: fgets()
That function always appends a NUL byte to the input and always stops 1 short of the length it is given, so there will be room for the NUL byte
regarding:
char a[3];
char b[3];
fgets(a, sizeof(a), stdin);
fflush(stdin);
fgets(b, sizeof(b), stdin);
fprintf(stderr, "%s%s", a, b)
replace:
fflush(stdin);
with:
int ch;
while( ( ch = getchar() ) != EOF && ch != '\n' ){;}
Upvotes: 0
Reputation: 8286
strchr
could be used to look for a newline. If found, set the newline to zero to terminate the string. Call fgets
to fill the remainder of the array. The loops continue until both arrays are filled.
The array with size [4] can store three characters and a terminating zero.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ( void) {
char a[4];
char b[4];
char *newline = NULL;
size_t len = 0;
fgets(a, sizeof(a), stdin);
while ( ( newline = strchr ( a, '\n'))) {//find a newline
*newline = 0;//set terminating zero
len = strlen ( a);
if ( len < sizeof a - 1) {//space available in array
fgets ( newline, sizeof a - len, stdin);//more input into array
}
else {
break;
}
}
fgets(b, sizeof(b), stdin);
while ( ( newline = strchr ( b, '\n'))) {//find a newline
*newline = 0;//set terminating zero
len = strlen ( b);
if ( len < sizeof b - 1) {//space available in array
fgets ( newline, sizeof b - len, stdin);//more input into array
}
else {
break;
}
}
fprintf(stderr, "%s%s\n", a, b);
return 0;
}
getchar
could be used to clear the input stream if the first array does not contain a newline.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ( void) {
char a[4];
char b[4];
fgets(a, sizeof(a), stdin);
if ( ! strchr ( a, '\n')) {//no newline
while ( '\n' != getchar ( )) {//clear the input stream
if ( EOF == getchar ( )) {
fprintf ( stderr, "problem EOF\n");
return 1;
}
}
}
fgets(b, sizeof(b), stdin);
fprintf(stderr, "%s%s\n", a, b);
return 0;
}
Upvotes: 1