1

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?

1 Answers1

0

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' );
}
Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
  • Thank you very much. I also used the below line after each scanf and got what i wanted. while((getchar()) != '\n'); – Amirhossein Bigdeli Jun 13 '20 at 14:35
  • @AmirhosseinBigdeli: Yes, that should also work. However, if [EOF is read from stdin](https://stackoverflow.com/q/3197025/12149471) (caused for example by piping stdin or the user manually entering EOF), then you may have an infinite loop. Therefore, checking for EOF is generally safer. But this is only a minor issue. I believe most implementations only return EOF once if it is manually entered by the user. – Andreas Wenzel Jun 13 '20 at 15:04
  • @AmirhosseinBigdeli: Generally, I wouldn't recommend using `scanf`, unless you know exactly what you are doing. You may want to read this guide: [A beginners' guide away from scanf()](http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html) – Andreas Wenzel Jun 13 '20 at 15:19