gpt4 book ai didi

C:打印二维数组的问题

转载 作者:行者123 更新时间:2023-11-30 15:03:08 25 4
gpt4 key购买 nike

我正在编写 C 代码,但在打印二维数组时遇到问题。它不是一次打印一个字符串,而是从要求的点打印整个数组。

例如,输入是“Dog”、“Cat”、“Hat”。然后它会打印出:

DogCatHat
CatHat
Hat

这就是我的代码应该做的事情:它从文件中读取。它创建一个 char 数组的数组。每个字符数组有 30 个字符,每次从文件中读取一个字符。然后它每行打印出一个字符数组。

代码如下所示:

char fname[] = "folder/text.txt";
char arry[30][30];
FILE *file;

file = fopen(fname, "r");
for(int x=0; x<30; x++){
for(int i=0; i<30; i++){
arry[x][i] = fgetc(file);
}
}

fclose(file);
for(int i=0; i<30; i++){
printf("%s\n", arry[i]);
}

很可能我刚刚犯了一个明显的错误,但我找不到它。所以请帮忙。

最佳答案

我认为文件中的字符串不是以空字符结尾的。所以你需要在数组的最后一个字符处放置空字符。

char arry[30][30]

for(int x=0; x<30; x++){
for(int i=0; i<29; i++){ //You can write 29 characters + '\0'
arry[x][i] = fgetc(file);
}
arry[x][29] = '\0';
}
for(int i=0; i<30; i++){
printf("%s\n", arry[i]);
}

关于C:打印二维数组的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40829778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com