If you enter more than five characters in the "name" field the function giving the wrong output, otherwise if the input is less than or equal to five characters the function works just fine, or if I use just %s
instead of reading five characters using %5s
then also the function works.
Is there any fix available (I want to use %5s
)?
#include<stdio.h>
int main(void)
{
char name[6];
int age;
printf("Enter your name: ");
scanf("%5s",name);
printf("Enter your age: ");
scanf("%d",&age);
printf("Your name: %.4s\n",name);
printf("Your age: %d\n",age);
return 0;
}
It's good that you limit the input to five characters, as that will make it fit perfectly in the array you have (including the terminator). However, if the user inputs a longer string, the remaining will be left in the buffer and the input of the age
will not work.
As a (relatively) simple way to improve input, use fgets
instead to read a line but increase array size as it can include the newline itself. And that's kind of the point here: If the buffer contains the newline, then you know you have read the full string, can replace it with the string terminator, and then move on. However, if the buffer doesn't contain a newline, you need to "flush" the input buffer by reading all the remaining characters of the line and ignore them.