c - 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 一起使用时它会出现故障?
感谢您的关注。
解决方案
推荐阅读
- r - 以对数刻度显示范围
- python - 如何在python中计算表面的不规则性
- spring-mvc - 类“javax.annotation.Nullable”的签名者信息与其他类的签名者信息不匹配
- android - 是否可以通过 Intent 在活动之间传递 URL?
- reactjs - ReactJS CoreUI - 如何在侧边栏项中使用 URL 路径参数
- azure-devops - 如何备份 Azure Devops 上的数据?
- mysql - 查询生成器返回不正确的日期时间比较查询结果
- openedge - 如何逃避更新消息?
- node.js - 防止在 MongoDB 查询中提供 _id 字段
- excel - VLookup 耗时太长 - 需要替代方案