简体   繁体   English

读取包含矩阵的ASCII文本文件到二维数组(C语言)

[英]Reading in a ASCII text file containing a matrix into a 2-D array (C language)

I have an ASCII file containing a matrix of real numbers. 我有一个包含实数矩阵的ASCII文件。 I want to read this matrix into a 2-D array in the C language. 我想把这个矩阵读成C语言的二维数组。 The ASCII file contains the 4x3 matrix looks like this: ASCII文件包含4x3矩阵,如下所示:

2 3 4
4 5 6.7
3 4 8.9
3 4 5.9

Can anyone suggest a quick way to do this? 谁能建议一个快速的方法来做到这一点? I have googled this but all solutions I see are pretty convoluted. 我用谷歌搜索了这个,但我看到的所有解决方案都非常复杂。

What about: 关于什么:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    double matrix[4][3];
    int i, j;
    for (i = 0; i < 4; i++)
    {
        for (j = 0; j < 3; j++)
        {
            if (scanf("%lf", &matrix[i][j]) != 1)
            {
                fprintf(stderr, "Failed to read matrix[%d][%d]\n", i, j);
                exit(1);
            }
        }
    }

    for (i = 0; i < 4; i++)
    {
        for (j = 0; j < 3; j++)
        {
            printf("%6.2f", matrix[i][j]);
        }
        putchar('\n');
    }

    return 0;
}

Example output 示例输出

  2.00  3.00  4.00
  4.00  5.00  6.70
  3.00  4.00  8.90
  3.00  4.00  5.90

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM