将CSV文件写入C中的向量(续)

时间:2011-02-12 06:21:18

标签: c++

基本上我有14800x8矩阵,它已从matlab中提取为CSV文件(“moves.mo”)。我需要将此文件读入14800个向量,每个向量具有8个值。 以下是文件中的几行:

1,2,3,4,-1,-3,-2,-4
1,2,3,5,-1,-3,-2,-5
1,2,3,6,-1,-3,-2,-6
1,2,3,7,-1,-3,-2,-7
1,2,3,8,-1,-3,-2,-8
1,2,3,9,-1,-3,-2,-9

我写了以下代码:

#include <iostream>
#include <fstream>
#include<stdio.h>
#include <string>
#include <istream>
#include <vector>
#include <sstream>
using namespace std;
int main()
{



        std::fstream inputfile;
        inputfile.open("moves.da");
        std::vector< std::vector<int> > vectorsmovesList; //declare vector list


        while (inputfile) {

            std::string s;
            if (!getline( inputfile, s )) break;

            istringstream ss( s );
            vector <int> recordmove;

            while (ss)
            {

                if (!getline( ss, s, ',' )) break;
                int recordedMoveInt = atoi(s.c_str());
                recordmove.push_back( recordedMoveInt );
            }

            vectorsmovesList.push_back( recordmove );
        }
        if (!inputfile.eof())
        {
            cerr << "Fooey!\n";
        }

它编译但不给我理想的输出(即只打印Fooey!)。我不知道为什么......这个问题在这一点上让我感到疯狂。

请帮忙!

1 个答案:

答案 0 :(得分:0)

有更好的方法可以在C ++中读取整数。例如:

std::string s;
if (!getline( inputfile, s )) break;
istringstream ss( s );
int recordedMove;
while (ss >> recordedMove)
{
    recordmove.push_back(recordedMove);
    // consume the commas between integers.  note if there are no 
    // separating commas, you will lose some integers here.
    char garbage; 
    ss >> garbage;
}

此外,您不会在任何地方打印出结果。这是你如何做到的:

vector<vector<int> >::const_iterator ii;
for (ii = vectorsmovesList.begin(); ii != vectorsmovesList.end(); ++ii)
{
    vector<int>::const_iterator jj;
    for (jj = ii->begin(); jj != ii->end(); ++jj)
        cout << *jj << ' ';
    cout << endl;
}

显然,在解析并关闭CSV文件后,您就会这样做。