c++ - 将文本文件读入矩阵

标签 c++ matrix

我正在尝试将文本文件中的数据读入矩阵。文本文件如下所示。

Object data
Format 6
1 5241.365147 -77215.356982 248612.514352 0.000014 0.000009 0.000051
2 5242.871592 -77213.351692 248614.103512 0.000013 0.000008 0.000052
...

我在本站之前的答案中搜索了类似的问题,并编写了以下代码。

#include <iostream>
#include <fstream>
#include <vector>

using namespace std

int main ()
{
// Initialize variables
int i, j, i_max, j_max;
i_max = 7;
j_max = 4;

//Open the input file
ifstream infile;
infile.open ("data.txt");

//Loop through the values in the text file
double data [i_max][j_max];
for (i=0; i<i_max; i++) {
    for (j=0; j<j_max; j++) {
        infile >> data[i][j];
        printf ("%d\n", data[i][j]); //Check the input 
    }
}

return 0;
}

我遇到的问题是我用来检查输入的 printf 语句只将 j_max 的值写入终端。任何帮助将不胜感激。

最佳答案

修复如下:-

i_max = 4; //this is no. of rows  
j_max = 7; // this is no. of cols 

std::string dummy;
getline(infile,dummy); //Skip 1st line "Object data"
getline(infile,dummy); //Skip 2nd line "Format 6"

double data [i_max][j_max];
for (i=0; i<i_max; i++) {
    for (j=0; j<j_max; j++) {
        infile >> data[i][j];
        // Use %f format specifier for floats
            printf ("%f\n", data[i][j]);  
    }
}

此外,请不要混用 C 和 C++

关于c++ - 将文本文件读入矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18380214/

相关文章:

c++ - const 字符串仍然更可取吗?

c++ - E2108 typedef 使用不当 'TJSONObject' 使用 GetValue 路径评估器时出错

matrix - 莫林矩阵与 Google Drive 电子表格

matlab - 在 matlab 中装箱

c - C : how to pass them as an argument to a function, 中未调整大小的矩阵在我的代码中操作并返回它们?

R:维度名称列表中的稀疏矩阵

c++ - 从 ESP8266 Arduino 连接到我的服务器

c++ - 接收大量 (r) UDP 流量时 CPU 负载高 (Windows)

c++ - 构造函数c++中指向不同类的指针初始化

python - Numpy:从两个向量(或一个向量本身)的笛卡尔积创建一个矩阵,同时将一个函数应用于所有对