c - 在循环中对带空格的字符串使用 scanf 时的有趣行为

标签 c string scanf

我在摆弄C,碰巧在下面写了代码。当我输入一个带空格的字符串时,程序接收所有输入,但输出它们就像它们在不同时间作为单个单词输入一样。我认为 scanf 在遇到第一个空白字符时停止并忽略其余部分。但事实似乎并非如此。

我在下面输入“inputWithNoSpaces”和“input with spaces”时包括了输出。

我试图查看标准输入。它接收所有输入。但是我不知道 scanf 在做什么。我想了解正在发生的事情。

代码:

#include <stdio.h>

int main()
{
    int i=0;
    char word[64]="";

    while(1)
    {
        printf("enter string:");
        scanf("%s",word);
        i++;
        printf("%d:%s\n\n",i,word);
    }

    return 0;
}

输出:

enter string:inputWithNoSpaces
1:inputWithNoSpaces

enter string:input with spaces
2:input

enter string:3:with

enter string:4:spaces

enter string:

最佳答案

scanf() 中,"%s" 表示“跳过空白字符,然后读取一系列非空白字符”。因此,当您给它输入 input with spaces 时,它将返回 "input""with""spaces" 在三个顺序调用中。这是预期的行为。有关更多信息,请阅读 manual page .

input with spaces
^^^^^                    First scanf("%s", s) reads this
     ^                   Second scanf("%s", s) skips over this whitespace
      ^^^^               Second scanf("%s", s) reads this
          ^              Third scanf("%s", s) skips over this whitespace
           ^^^^^^        Third scanf("%s", s) reads this

关于c - 在循环中对带空格的字符串使用 scanf 时的有趣行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43912347/

相关文章:

c - 小数点后N位C四舍五入

Haskell 中带列表的字符串替换运算符

sql - 如何在 SQL Server 中使用预定义的特殊字符修剪字符串?

ios - 计算 UILabel 的一行可以容纳多少个字符

c++ - 解析(浮点)数字时使用什么信息?

c - 快速排序特例 - 似乎是 K&R 的错误算法

c - 如何使用指针更改字符串中的字符?

c - 在 C 中,我使用 bool 逻辑通过 while 循环转到程序的开头,但是在我告诉它们之后,我的变量没有重新初始化

c - 如何从控制台读取图形而不知道它有多少条边?

c - 我需要有关scanf()的帮助