gpt4 book ai didi

c - 将 C 数组打印到终端

转载 作者:太空宇宙 更新时间:2023-11-04 00:15:30 24 4
gpt4 key购买 nike

我需要从 C 中读入一个文件,将其存储在一个数组中并打印其内容。出于某种原因,我一直在接近尾声的输出中看到八进制。在打开文件后计算其中有多少行和字符后,我正在动态创建数组。

输出:

Abies 
abies
abietate
abietene
abietic
abietin
\320ѿ_\377Abietineae --> umlaut? where did he come from?
y\300_\377abietineous

代码:

int main(int argc, char ** argv) {

char c = '\0';
FILE * file;
int i = 0, j = 0, max_line = 0, max_char_per_line = 0;

/* get array limits */
file = fopen(argv[1], "r");
while ((c = fgetc(file)) != EOF){
if (c == '\n'){
max_line++; j++;
if (j > max_char_per_line){
max_char_per_line = j;
}
j = 0;
continue;
}
j++;
}

rewind(file);
/* declare array dynamically based on max line and max char */
char word[max_line][max_char_per_line];

/*read in file*/
j = 0; c = '\0';

while ((c = fgetc(file)) != EOF){
if (c == '\n'){
word[i][j] = '\0';
i++; j=0;
continue;
}

word[i][j] = c;
j++;
}
word[i][j] = '\0';

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



return 0;
}

最佳答案

更改读取例程:

   if (c == '\n'){
word[i][j] = 0x0;
i++; j=0;
continue;
}

并在 printf 例程中添加“\n”。

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

C 字符串以零结尾,而不是以“\n”结尾,因此当您对它们进行 printf() 处理时,printf() 不知道在哪里停止打印。

关于c - 将 C 数组打印到终端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12732470/

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