2014-08-30 14 views
0

例如:如何在C++中讀取不同的格式?

Adam Peter Eric 
John Edward 
Wendy 

我想在3串陣列(每行表示一個數組)來存儲,但我被困關於如何逐行讀取它。

這裏是我的代碼:

string name [3][3] ; 
ifstream file ("TTT.txt"); 
for (int x = 0; x < 3; x++){ 
    for (int i = 0; x < 3; i++){ 
     while (!file.eof()){ 
      file >> name[x][i]; 
     } 
    } 
} 

cout << name[0][0]; 
cout << name[0][1]; 
cout << name[0][2]; 

cout << name[1][0]; 
cout << name[1][1]; 
cout << name[2][0]; 

}

回答

1

您可以使用std::getline()

std::ifstream file ("TTT.txt"); 
std::string line; 
std::string word; 
std::vector< std::vector<std::string> > myVector; // use vectors instead of array in c++, they make your life easier and you don't have so many problems with memory allocation 
while (std::getline(file, line)) 
{ 
    std::istringstream stringStream(line); 
    std::vector<std::string> > myTempVector; 

    while(stringStream >> word) 
    { 
     // save to your vector 
     myTempVector.push_back(word); // insert word at end of vector 
    } 
    myVector.push_back(myTempVector); // insert temporary vector in "vector of vectors" 
} 

使用STL結構,C++(矢量地圖,對)。他們通常會讓你的生活更輕鬆,並且你的內存分配問題也更少。

+0

你有行1文件,並在第3行 – LeppyR64 2014-08-30 22:58:06

+0

INFILE沒有看到,糾正它。謝謝 – 2014-08-30 22:59:17

+0

我想將它存儲在二維數組中,並且位置確實很重要。 Adam應該是名字[0] [0],John = name [1] [0] wendy = name [2] [0] – Vanishadow 2014-08-30 23:26:41

1

您可以使用std::getline直接閱讀完整的一行。之後,只需使用空格作爲分隔符獲取單個子:

std::string line; 
std::getline(file, line); 
size_t position; 
while ((position =line.find(" ")) != -1) { 
    std::string element = line.substr(0, position); 
    // 1. Iteration: element will be "Adam" 
    // 2. Iteration: element will be "Peter" 
    // … 
} 
相關問題