2

我有一个包含数千个浮点值的数据文件,我想将它们读入二维向量数组,并在存储文件中的浮点数后将该向量传递给另一个例程。当我运行此代码时,它会打印出来;

[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();
4

3 回答 3

6

在我看来,文件无法打开。你没有测试成功,所以无论如何它都会继续前进。您所有的值都被初始化为零,并且会保持这种状态,因为每次读取都失败。这是猜想,我承认,但我会投入资金。=)

于 2012-10-15T00:57:53.420 回答
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;
}
于 2012-10-15T09:05:47.573 回答
-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;
}
于 2012-10-15T01:19:54.423 回答