【问题标题】:switch from 2d array to 1d (string)从二维数组切换到一维(字符串)
【发布时间】:2016-01-15 02:11:35
【问题描述】:

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

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

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

【问题讨论】:

  • 这个问题已经回答了很多次了。对于初学者,请参阅return 2d array from function。使用 line-oriented 输入函数来读取 lines 的数据...

标签: c arrays string malloc


【解决方案1】:

您应该跳过每行末尾的'\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]);
}

【讨论】:

    猜你喜欢
    • 2015-01-21
    • 2021-06-12
    • 1970-01-01
    • 2019-01-23
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多