gpt4 book ai didi

c - 从二维数组切换到一维(字符串)

转载 作者:太空宇宙 更新时间:2023-11-04 03:32:59 25 4
gpt4 key购买 nike

我正在尝试读取具有类似内容的文件的输入

RGGG
RGYY
YYYY

因此,我正在尝试获取包含每个提到的字符串的字符串数组(如果需要,还可以获取更多)。到目前为止,我将输入输入到一个二维数组中,但我似乎无法弄清楚将读取的字符放入一个字符串数组中。

char ch, file_name[100];
FILE *fp;

printf("Enter the name of file you wish to see\n");
scanf("%s", file_name);

fp = fopen(file_name, "r"); // read mode

if (fp == NULL) {
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}

printf("The contents of %s file are :\n", file_name);

Matrix = (char **)malloc(4 * sizeof(char *));
for (int i = 0; i < 4; i++)
Matrix[i] = (char*)malloc(8 * sizeof(char));

for (int i = 0; i < 4; i++) {
int j = 0;
while (j < 4 && fscanf(fp, "%c", &Matrix[i][j++]) == 1);
}

for (i = 0; i < 4; i++) {
for (j = 0; j < 8; j++) {
printf("Matrix[%d][%d] = %c\n", i, j, Matrix[i][j]);
}
}

这是打印类似的东西:

Matriz[0][0] = R
Matriz[0][1] = G
Matriz[0][2] = G
Matriz[0][3] = G
Matriz[0][4] =

Matriz[0][5] = R
Matriz[0][6] = G
Matriz[0][7] = Y
Matriz[1][0] = Y
Matriz[1][1] =

Matriz[1][2] = Y
Matriz[1][3] = Y
Matriz[1][4] = Y
Matriz[1][5] = Y
Matriz[1][6] = ═
Matriz[1][7] = ═

希望获得一些见解:

string[0] = RGGG
string[1] = RGYY
string[2] = YYYY

我只是遗漏了一些非常明显的东西吗?谢谢。

最佳答案

你应该跳过每行末尾的'\n':

for (int i = 0; i < 4; i++) {
int j = 0;
while (j < 4 && fscanf(fp, "%c", &Matrix[i][j++]) == 1);
getc(fp);
}

或者更简单:

for (int i = 0; i < 4; i++) {
memset(Matrix[i], 0, 8);
fscanf(fp, "%7s", Matrix[i]);
}

并以这种方式转储字符串:

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

关于c - 从二维数组切换到一维(字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34803289/

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