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?

2
  • You could use scanf("%4s %*[^\n]%*c", name[0]); but it's not safe to any possible input. Commented Jun 13, 2020 at 14:12
  • You cannot use scanf for interactive user input apart for test and toy programs. Consider using fgets and parse the resulting string yourself. Commented Jun 13, 2020 at 14:15

1 Answer 1

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' );
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much. I also used the below line after each scanf and got what i wanted. while((getchar()) != '\n');
@AmirhosseinBigdeli: Yes, that should also work. However, if EOF is read from stdin (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.
@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()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.