I want to read two strings from input like the code below. The problem is when the user enters a string with a longer size that causes overflow. for example if user enters "steven" as name[0], the second scanf() won't work and the result is name[0]="stev" and name[1]="en". My desired output is name[0]="stev" and name[1] be at most the 4 characters read using second scanf(), for example name[1]="gabr" if the input is gabriel. I tried fflush(stdin) before second scanf() and also fgets instead of scanf but none of them helped.
#include <stdio.h>
int main()
{
char name[2][5];
printf("Enter name1: \n");
scanf("%4s", name[0]);
//fflush(stdin);
printf("Enter name2: \n");
scanf("%4s", name[1]);
for(int i=0 ; i<2 ; i++)
printf("You entered: %s\n", name[i]);
return 0;
}
anyone can help me with this please?
I suggest you use fgets
instead of scanf
, like this:
fgets( name[0], 5, stdin );
That way, you can check whether a newline was consumed by fgets
(scanf
does not provide this information) and if not, consume the rest of the line:
int len = strlen( name[0] );
if ( len > 0 && name[0][len-1] != '\n' )
{
//a newline was not read by fgets, so we must consume the
//rest of the line up to and including the '\n' character
int c;
while ( ( c = fgetc( stdin) ) != EOF && c != '\n' );
}