C - 从 2D 数组切换到 1D(字符串)



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

RGGG
RGYY 
YYYY

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

char ch, file_name[100];
FILE *fp;
printf("Enter the name of file you wish to seen");
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] = %cn", 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] = %sn", i, Matrix[i]);
}

相关内容

  • 没有找到相关文章

最新更新