【问题标题】:Why cant scanf read white spaces?为什么 scanf 不能读取空格?
【发布时间】: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()。它有很多优点,包括它可以避免你遇到的问题。

标签: c scanf fgets


【解决方案1】:

为什么 scanf 不能读取空格?

这是一个错误的问题,因为scanf() 确实读取了空格。

scanf() 从stdin 读取并给出各种指令和说明符,尽力匹配它们。一些说明符导致scanf() 保存数据。

"%d" 指定scanf() 为:
1- 读取并丢弃所有空白。
2- 读取数字文本并将其转换为int,将结果保存到i。
3- 继续第 2 步,直到读取到一个非数字字符,该字符返回到stdin。
4- 如果第 2 步成功,则返回 1。如果步骤 2 仅遇到非数字输入,则返回 0。否则返回EOF。

int i;
if (1 == scanf("%d", &i)) GoodToGo();

除"%c"、"%n"、"%[]" 之外的所有scanf() 格式说明符,首先读取并丢弃前导空格。


"%c" 指定scanf() 为:
将char 读入c,包括任何空白字符。
返回 1 或 EOF。

char c;
if (1 == scanf("%c", &c)) GoodToGo();

scanf() 和家庭详细信息在这里无法简单回答。详情请查看在线资源。


使用fgets() 读取一行比使用scanf(any_format) 更好

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2022-01-20
    • 2022-01-17
    相关资源
    最近更新 更多