c - 为什么字符串中包含的空格不起作用?
问题描述
#include <stdio.h>
#include <stdlib.h>
int main()
{
char firstname[15];
char lastname[15];
char crush_first[15];
char crush_last[15];
int babies;
printf("What is your first name?\n");
scanf("%s", firstname );
printf("What is your last name?\n");
scanf(" %s", lastname);
/* see i have added space before the character conversion but on exectution
of this file no space is in between the two strings*/
printf("What is your crush's first name?\n");
scanf("%s", crush_first );
printf("What is your crush's last name?\n");
scanf(" %s", crush_last );
printf("How many kids will you have?");
scanf("%d", &babies );
printf("%s%s will have a lovely marriage with %s%s and they will have %d kids",firstname,lastname,crush_first,crush_last,babies);
}
现在我要做的是在字符串中默认添加空格。“__etc”我希望字符串也存储这些值。虽然我在 %s 之前反复添加了空格,但它无法识别。
解决方案
来自scanf 文档:
s matches a sequence of non-whitespace characters (a string) [...]
此外,如果有人输入的字符串比您的接收缓冲区长,您将溢出缓冲区。
如果您想阅读该行直到换行,也许可以使用 fgets:
fgets(lastname, sizeof(lastname), stdin);
推荐阅读
- python - 从多语言 Unicode 文本中删除表情符号
- android - FragmentTransaction 中的片段 getView() 方法为 NULL
- paging - 启用分页时,xen 中的 ARM 启动代码无法启动
- jakarta-ee - 升级 weblogic 时在控制台中收到警告:无法为应用程序添加 Jersey servlet
- java - 我可以在 ios 开发的 xcode 项目中使用 java 库(瑞士星历表)吗?
- ruby - 如何重新创建任何?Ruby中的方法
- opencart - 将哈希更新为 HMAC-SHA-512
- powershell - 在 PowerShell 并行工作流中将输出导出到 CSV 时出现问题
- angular - Mat-Menu 上 Angular-Material 的角度测试
- android - 谷歌地图黑线