在C ++中读取浮动文本文件为二维矢量

时间:2012-10-15 00:35:06

标签: c++ arrays vector fstream ifstream

我有一个由数千个浮点值组成的数据文件,我希望将它们读入2D矢量数组,并将该矢量传递给另一个例程,一旦它存储了文件中的浮点数。当我运行此代码时,它打印出来;

  

[0] [0] = 0,[0] [1] = 0等

数据文件包含像

这样的值
  

0.000579,27.560021等

int rows = 1000;
int cols = 2;
vector<vector<float>> dataVec(rows,vector<float>(cols));
ifstream in;
in.open("Data.txt");

for(int i = 0; i < rows; i++){
    for(int j = 0; j < 2; j++){
        in >> dataVec[i][j];    
        cout << "[ " << i << "][ " << j << "] = " << dataVec[i][j] << endl;
    }
}
in.close();

3 个答案:

答案 0 :(得分:6)

我认为该文件无法打开。你没有测试成功,所以无论如何都要努力。您的所有值都初始化为零,并且将保持这种状态,因为每次读取都会失败。我承认,这是猜想,但我会把钱投入其中。 =)

答案 1 :(得分:1)

尝试此解决方案,它可以根据您的规格运行:

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;

int main(void)
{

    ifstream infile;
    char cNum[10] ;
    int rows = 1;
    int cols = 2;
    vector<vector<float > > dataVec(rows,vector<float>(cols));

    infile.open ("test2.txt", ifstream::in);
    if (infile.is_open())
    {
            while (infile.good())
            {

                for(int i = 0; i < rows; i++)
                {
                    for(int j = 0; j < 2; j++)
                    {

                        infile.getline(cNum, 256, ',');

                        dataVec[i][j]= atof(cNum) ;

                        cout <<dataVec[i][j]<<" , ";

                    }
                }



            }
            infile.close();
    }
    else
    {
            cout << "Error opening file";
    }

    cout<<" \nPress any key to continue\n";
    cin.ignore();
    cin.get();


   return 0;
}

答案 2 :(得分:-1)

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

using namespace std;

void write(int m, int n)
{
    ofstream ofs("data.txt");
    if (!ofs) {
        cerr << "write error" << endl;
        return;
    }

    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
            ofs << i+j << " ";
}

void read(int m, int n)
{
    ifstream ifs("data.txt");
    if (!ifs) {
        cerr << "read error" << endl;
        return;
    }

    vector<float> v;
    float a;
    while (ifs >> a) v.push_back(a);

    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
            cout << "[" << i << "][" << j << "] = "
                 << v[i*n+j] << ", ";
}

int main()
{
    write(2,2);
    read(2,2);

    return 0;
}