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

How to read different formats in C++?

本文关键字:格式 C++      更新时间:2023-10-16

例如:

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

}

您可以使用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"
  // …
}

您可以使用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++中使用stl结构(向量、映射、对)。它们通常会让你的生活更轻松,你在内存分配方面的问题也更少。