scanf()
leave the following \n from the end of that line in the buffer where fgets()
will read it. To slove this we have to do something to consume the newline. Let's see the problem.
The problem
#include
void main()
{
char input[10];
printf("Enter in fgets: ");
scanf("%s", input);
getchar();
printf("Enter in scanf: ");
fgets(input, 10, stdin);
}
Output:
Enter in scanf: Hello
Enter in fgets:
As you can see that it dons't show the fgets part. Let's see the solution.
Put getchar()
between scanf and fgets()
#include
void main()
{
char input[10];
printf("Enter in fgets: ");
scanf("%s", input);
getchar();
printf("Enter in scanf: ");
fgets(input, 10, stdin);
}
Output:
Enter in scanf: Hello
Enter in fgets: Hello
If it's possible use scanf()
after the fgets()
#include
void main()
{
char input[10];
printf("Enter in fgets: ");
fgets(input, 10, stdin);
getchar();
printf("Enter in scanf: ");
scanf("%s", input);
}
Output:
Enter in fgets: Hello
Enter in scanf: Hello
Put fget()
2 times(This method don't work some time)
#include
void main()
{
char input[10];
printf("Enter in fgets: ");
scanf("%s", input);
getchar();
printf("Enter in scanf: ");
fgets(input, 10, stdin);
fgets(input, 10, stdin)
}
Output:
Enter in scanf: Hello
Enter in fgets: Hello
Put sscanf()
inseted of scanf()
#include
void main()
{
char input[10];
printf("Enter in fgets: ");
sscanf(hello, "%s", input);
getchar();
printf("Enter in scanf: ");
fgets(input, 10, stdin);
}
Output:
Enter in sscanf: Hello
Enter in fgets: Hello