打印char多维阵列无法正常工作

发布于 2025-01-19 12:01:46 字数 772 浏览 1 评论 0原文

#include <stdio.h>

int main()
{
    FILE *fisier;
    fisier = fopen("cnp.txt", "r");

    int cnpuri = 0;
    char cnp[10][13];

    while(1){
        fscanf(fisier, "%s", cnp[cnpuri]);
        cnpuri++;

        if(feof(fisier))
            break;
    }

    int i;
    for(i = 0; i < cnpuri; i++){
        printf("%s \n", cnp[i]);
    }

    fclose(fisier);
    return 0;
}

这是我正在阅读的文本:

1234567890123
1763578126765
4156156546489
5749684631654
5498654168763

这就是它在终端中显示的内容:

12345678901231763578126765415615654648957496846316545498654168763
1763578126765415615654648957496846316545498654168763
415615654648957496846316545498654168763
57496846316545498654168763
5498654168763
#include <stdio.h>

int main()
{
    FILE *fisier;
    fisier = fopen("cnp.txt", "r");

    int cnpuri = 0;
    char cnp[10][13];

    while(1){
        fscanf(fisier, "%s", cnp[cnpuri]);
        cnpuri++;

        if(feof(fisier))
            break;
    }

    int i;
    for(i = 0; i < cnpuri; i++){
        printf("%s \n", cnp[i]);
    }

    fclose(fisier);
    return 0;
}

This is the text I'm reading:

1234567890123
1763578126765
4156156546489
5749684631654
5498654168763

And this is what it shows in terminal:

12345678901231763578126765415615654648957496846316545498654168763
1763578126765415615654648957496846316545498654168763
415615654648957496846316545498654168763
57496846316545498654168763
5498654168763

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

扭转时空 2025-01-26 12:01:46

问题在于,阵列的第二尺寸

char cnp[10][13];

不足以存储输入字符串的终端零特征。

至少像这样声明它

char cnp[10][14];    

也可以更改以下方式

while( cnpuri < 10 && fscanf(fisier, "%s", cnp[cnpuri]) == 1)
{
    cnpuri++;
}

The problem is that the second size of the array

char cnp[10][13];

is not large enough to store the terminating zero character of entered strings.

Declare it at least like

char cnp[10][14];    

Also change the while loop the following way

while( cnpuri < 10 && fscanf(fisier, "%s", cnp[cnpuri]) == 1)
{
    cnpuri++;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文