首页 > 解决方案 > C - scanf 没有像我预期的那样处理空间

问题描述

作为编码的初学者,我正在学习关于 C 的免费课程,目前正在尝试理解字符串。

为了测试事情,我一直在写以下内容:

#include <stdio.h>
#include <stdlib.h>


int main()
{
    char test[] = "What's your name ?\n\n";
    char firstName[100];
    char lastName[100];

    printf("%s", test);

    printf("What's your first name ?\n");
    scanf("%s", firstName);

    printf("What's your last name ?\n");
    scanf("%s", lastName);

    printf("Your name is %s %s", firstName, lastName);


    return 0;
}

当我运行它时,第一个 printf() 正常显示 test[] 。

仅当 firstName 或 lastName 中没有空格时,程序的其余部分才能正常工作。

如果 firstName 中有空格,程序将跳过第二个 scanf 并显示 firstName。如果 firstName 中有两个空格,程序将跳过第二个 scanf 并仅显示 firstName 中的前两个单词。如果 lastName 中有空格,程序将显示 firstName 并且仅显示 lastName 中的第一个单词。

我不明白为什么会这样,尤其是当 firstName 中有空格时为什么会跳过第二个 scanf。第一个 printf 表明应该毫无问题地处理空格,那么为什么当我将它们与 scanf 一起使用时它会出现故障?

感谢您的关注。

标签: c

解决方案


推荐阅读