c - 数组不在 C 中存储/显示整个字符串
问题描述
所以我有这个代码:
char address[1000] ;
printf("Enter you address : ") ;
scanf("%s", &address) ;
printf(" Your address is : %s ", address) ;
当我输入例如“纽约市”时,只会显示“新”,我不知道为什么。请帮忙。谢谢
解决方案
那么你可以使用:
scanf(" %999[^\n]", address )
但使用起来可能会更好(也许更安全)fgets
:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char address[1000] ;
printf("Enter you address : ") ;
if ( fgets( address, sizeof(address), stdin) == NULL )
{
printf("Deal whith the Error\n");
exit( EXIT_FAILURE );
}
printf("Your address is : %s ", address);
}
输出:
Enter you address : New York City
Your address is : New York City
@Chris Dodd 在其评论中提到,关于fgets
并且可能您应该知道(如果您还不知道)fgets
添加了'\n'
。
如果您不需要它,您可以借助该strcspn
功能将其删除:
address[ strcspn( address, "\n" ) ] = 0;
您需要包括string.h
.
推荐阅读
- javascript - 使用输入字段中的数据填充确认/弹出框,并允许用户在 html 和 jquery 中进行编辑
- python - 运行 xgboost 算法给出编译错误
- node.js - Elasticsearch 创建连接字段(Nodejs)
- javascript - React-redux 正在分派一个 API 操作,当请求发送回 401 错误时
- svn - SVN 网页用户界面
- arrays - 从 Flutter 中的字符串写入 Firestore 中的数组
- javascript - 聚合不给出任何结果
- ios - textureGrad 函数 – 等效金属 (MSL)
- jquery - 使用 jQuery/getClientRects() 检测元素是否包装
- javascript - 如何在 react js. 中从 .js 文件中导入容器组件,以便在其他 .js 文件中用作弹出模式