2016-04-21 19 views
-4

我有文本的某些行文本文件讀入C++中的2D verctor

我希望把文成二維矢量一個文本文件,因爲我 需要能夠seperatly調用每個字[X] [ Y]

這是我得到了什麼: 我在迷宮得到一個錯誤[i] [j] = 「\ 0」

int main() { 
    // Variable declarations 
    fstream file; 
    int i=0; 
    vector<vector<char> > maze(1,vector<char>(1)); 

ifstream myReadFile; 
myReadFile.open("input.txt"); 

while (!myReadFile.eof()) { 


     for (int j=0; maze[i][j] != "\0"; j++){ 
      myReadFile >> maze[i][j]; 
     } 
    i++; 

} 

    file.close(); 
    for (int i = 0; i < maze.size(); i++) 
    { 
     for (int j = 0; j < maze[i].size(); j++) 
     { 
      cout << maze[i][j]; 
     } 
    } 
     return 0; 
} 

我發現,幾乎一個解決方案:

#include <fstream> 
#include <stdio.h> 
#include <string> 
#include <sstream> 

using namespace std; 

template <typename T> //T could be of any data type 
void printVector(T dvalue){//print the input data 
cout<<"List of the stored values "<<endl; 
for(int i=0; i<dvalue.size(); i++){ 
for(int j=0; j<dvalue[i].size(); j++){ 
cout<<dvalue[i][j]<<" "; 
} 
cout<<endl; 
} 
} 

int main(int argc, char* argv[]){ 
     cout<<"This example utilizes multi-dimensional vectors to read an input data file!"<<endl; 
     vector< vector<string> > dvalue; //multidimensional vector declaration 
     string line; 
     fstream myfile; //define a myfile object of fstream class type 
     myfile.open("input.txt"); //open the file passed through the main function 

//read 1 line at a time.If the data points are seperated by comma it treats as a new line 
     while(getline(myfile,line,'\n')){ 
       vector <string> v1; 
       istringstream iss(line);//read the first line and store it in iss 
       string value; 
//this line breaks the row of data stored in iss into several columns and stores in the v1 vector 
       while(iss>>value){ 
         v1.push_back(value); 
       } 
       dvalue.push_back(v1);//store the input data row by row 
     } 
     printVector(dvalue); 
return 0; 
} 

但是這個不能處理多個空格,它將它們輸出爲一個爲什麼?

+1

這是什麼都與C99辦?你的意思是C++ 98嗎? – NathanOliver

+2

_「在c99」_中,但標記爲[tag:C++] ?? –

+0

http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong –

回答

0

我可能會看到幾個錯誤。

  1. 將矢量定義爲1的大小,但嘗試使用直接索引添加更多元素。它導致異常。你應該使用push_back來添加更多的元素。

  2. 如果你想檢查行尾,字符是'\ r'和'\ n';

  3. 如果要比較字符,則使用'\ 0'而不是「\ 0」。

因此,這裏的推薦代碼:

int main() { 
// Variable declarations 
fstream file; 
vector<vector<char> > maze; 

ifstream myReadFile; 
myReadFile.open("input.txt"); 
vector <char> line; 
char c; 
while (!myReadFile.eof()) { 
    myReadFile.get(c); 
    if (c == '\r') 
    { 
     myReadFile.get(c); 
     if (c == '\n') 
     { 
      if (line.size() > 0) 
       maze.push_back(line); 
      line.clear(); 
      continue; 
     } 
    } 
    line.push_back(c); 

} 

file.close(); 
for (int i = 0; i < maze.size(); i++) 
{ 
    for (int j = 0; j < maze[i].size(); j++) 
    { 
     cout << maze[i][j]; 
    } 
} 
    return 0; 
} 
+0

您也可以使用'getline()',但您需要預先定義一個固定的空間緩衝區。如果尺寸不夠,可能會有潛在的問題。 –