2011-02-12 38 views
0

基本上我已經將14800x8矩陣從matlab中提取爲CSV文件(「moves.mo」)。我需要將這個文件讀入14800個具有8個值的向量。 下面是從文件中的幾行:將CSV文件寫入C中的矢量(續)

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 

我寫了下面的代碼:(!即只打印Fooey)

#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"; 
     } 

它編譯但不給我理想的輸出。我不知道爲什麼......這個問題在這一點上令我瘋狂。

請幫忙!

+2

很高興有一個鏈接到以前的帖子,但你不應該要求其他人跟着它來理解這個問題。請讓問題自成一體。 – 2011-02-12 06:26:19

+1

您可能還想解釋發生了什麼問題; 「這是行不通的」並不多。 – 2011-02-12 06:29:30

回答

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文件後,你應該這樣做。