Reputation: 327
Why does scanf not read white spaces?
Also in my code if I use scanf first then fgets or scanf the second time after a few lines, as you can see in the code, then if I give an input that has a space like, "Hey How are u" then my code loops, why so?
I fixed it by just using fgets
while(1)
{
entry=&entry_var;
*entry=0;
printf("\n++++++++DFS CLIENT MENU++++++++");
printf("\n1- ENTER THE COMMAND");
printf("\n2- EXIT\n");
/*instance 1:if I use scanf here then whether i use scanf or fgets the
second time it loops in *entry==1 */
fgets (command, sizeof(command), stdin);
*entry=atoi(command);
printf("Entry: %d", *entry);
if(*entry==1)
{
printf("\n--------COMMANDING ZONE--------");
printf("\nInput the Function: ");
//This is the second instance
fgets (command, sizeof(command), stdin);
//scanf("%s",command);
printf("\n%s",command);
command_parse(command);
}
else if(*entry==2)
{
break;
}
}
Upvotes: 0
Views: 530
Reputation: 153338
Why cant scanf read white spaces?
This is a false question as scanf()
does read white spaces.
scanf()
reads from stdin
and given various directives and specifiers, does its best to match them. Some specifiers cause scanf()
to save data.
"%d"
specifies scanf()
to:
1- Read and discard all white-space.
2- Read and covert numeric text into an int
, saving the result into i
.
3- Continue step 2 until reading a non-numeric character, which is returned to stdin
.
4- Return 1 if step 2 successful. Return 0 if step 2 only encountered non-numeric input. Else return EOF
.
int i;
if (1 == scanf("%d", &i)) GoodToGo();
All scanf()
format specifiers except "%c"
, "%n"
, "%[]"
, first read and discard leading white-space.
"%c"
specifies scanf()
to:
Read a char
into c
, including any whitespace character.
Return 1 or EOF.
char c;
if (1 == scanf("%c", &c)) GoodToGo();
scanf()
and family details are beyond a simple answer here. Check on-line resources for details.
Better to use fgets()
to read a line than scanf(any_format)
Upvotes: 1