please find the below code for example
main()
{
int i;
char s[100];
printf("Enter the string \n");
scanf(" %s ",s);
printf("Enter the string\n");
scanf("%d",&i);
printf("%s\n%d\n",s,i);
}
The output of above code is
Enter the string
hai
hai
Enter the string
hai
0
It supposed to accept one line input but it is accepting second line also.
If removed the space in scanf, the output is coming correctly.
Can anyone explain?
when using the same with integer (%d) it is not happening. It is happening with string.
our first scanf wait a string containing a space at the begginingbut it there is not. so it ask you agin to enter the string and in the second time is accepted because you type [enter] before entering your new string. The [enter] is treated in scanf as a white space.
Refer to this link it seems the same
Explain what is difference between without whitespace in scanf and with whitespace in scanf?