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

标签 c arrays string malloc

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

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/

相关文章:

c - 检查字母字符的函数

c - 如何在 C 中创建数组的 scanf 和 printf 函数?

arrays - 如何使用jq检查数组中是否存在元素

swift - 如何在 Swift 中证明 String 类型的 "copy-on-write"

c - 为什么在成熟的 C 项目的 Makefile 中不考虑对头文件的更改?

c - 在二维数组中查找 8 个邻居

javascript - 基于字符串变量将二维数组项添加到新数组

python - 对 numpy 屏蔽数组的操作给出屏蔽的无效值

python - Python 中的 SciPy 层次字符串聚类?

c++ - 将 std::string 转换为 LPCSTR 时的奇怪行为