I just started learning on C, I was trying to do some exercises. There is an exercise that wants me to take input for a character,a word and a sentence then print it. I tried to take all three input with scanf but when I execute the code program wants the first two inputs but skips the third input and prints the first two. I tried fgets and gets functions too but I couldn't solve the problem.
#include <stdio.h>
#include <string.h>
int main()
{
char ch;
char s[100];
char sen[100];
scanf("%c", &ch);
scanf("%s", &s);
scanf("%[^\n]%*c",sen);
printf("%c", ch);
printf("\n%s", s);
printf("\n%s", sen);
return 0;
}
I tried scanf, fgets and gets to enter all the inputs but I couldn't take and print all of them.
The problem is that this call of scanf
encounters a new line character
'\n'that is stored in the input buffer due to pressing the key Enter in the preceding call ofscanfand thus reads an empty string.Also in this case
the second argument expression has invalid type
char ( * )[100]instead ofchar *.Write instead
Pay attention to the leading space in the format string in the third call of scanf. It allows to skip white space characters in the input buffer.
In the first call of
scanfyou also may place a leading space in the format stringIt will be useful for example when you read characters in a loop and need to skip the new line character
'\n'of a preceding call ofscanf.As for this call with the conversion specifier
sthen the function automatically skips white space characters until a non white space character is encountered. Do placing a leading space in the format string is redundant.