如何在C ++中阅读不同的格式?

时间:2014-08-30 22:51:16

标签: c++ file

例如:

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];

}

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

在c ++(vector,map,pair)中使用stl结构。它们通常可以让您的生活更轻松,内存分配问题更少。

答案 1 :(得分: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"
  // …
}