Home > Blockchain >  scanf() overwrits next variable
scanf() overwrits next variable

Time:10-10

I am trying to get input from a user.

void InfoPrint(){
    char FirstName[20];
    char LastName[20];
    int BirthYear;
    printf("Input your First Name: ");
    scanf("s", FirstName);
    printf("\nInput your Last Name: ");
    scanf("s", LastName);
    printf("\nInput your year of birth: ");
    scanf("M", &BirthYear);
    printf("\n%s %s %d\n", FirstName, LastName, BirthYear);
}

Why when I input more then 19 characters in FirstName or LastName it overwrites my next variable?

CodePudding user response:

It is because the input buffer still contains characters that will be read by a next call of scanf.

So if you entered for example 30 characters and pressed the Enter key then the first 19 characters will be read by the first call of scanf

scanf("s", FirstName);

and the 11 remaining characters will be read by the second call of scanf.

scanf("s", LastName);

Or for example if you will enter a sequence of characters that contains a space character like "Hello World!" then the first call of scanf will read the word "Hello" and the second call of scanf will read the sequence "World!".

  • Related