数组不要 store/displah C 中的整个字符串
Array don't store/displah whole string in C
所以我有这个代码:
char address[1000] ;
printf("Enter you address : ") ;
scanf("%s", &address) ;
printf(" Your address is : %s ", address) ;
当我输入例如"New York City"时,只会显示"New",我不知道为什么。请帮忙。
谢谢
你可以使用:
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
.
所以我有这个代码:
char address[1000] ;
printf("Enter you address : ") ;
scanf("%s", &address) ;
printf(" Your address is : %s ", address) ;
当我输入例如"New York City"时,只会显示"New",我不知道为什么。请帮忙。 谢谢
你可以使用:
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
.