首页 > 解决方案 > 数组不在 C 中存储/显示整个字符串

问题描述

所以我有这个代码:

char address[1000] ;

printf("Enter you address : ") ;
scanf("%s", &address) ;

printf(" Your address is : %s ", address) ;

当我输入例如“纽约市”时,只会显示“新”,我不知道为什么。请帮忙。谢谢

标签: carraysstringprogramming-languages

解决方案


那么你可以使用:

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.


推荐阅读