【发布时间】:2015-10-24 01:14:19
【问题描述】:
为什么 scanf 不读取空格?
在我的代码中,如果我首先使用 scanf,然后在几行后第二次使用 fgets 或 scanf,正如您在代码中看到的那样,那么如果我输入的输入中包含空格,例如“Hey How are u”然后我的代码循环了,为什么会这样?
我只使用 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;
}
}
【问题讨论】:
-
Erm ... 因为它是这样指定的?
-
scanf用于读取和解析数字和单词等标记。空格是标记之间的分隔符,它通常会跳过它们。 -
@AnuragAzad
while (getchar() != '\n');应该这样做。 -
使用
fgets()读取数据行;当你想解析数据行时使用sscanf()。它有很多优点,包括它可以避免你遇到的问题。