如何从文件中读取多行

How do I read multiple lines from a file?

本文关键字:读取 文件      更新时间:2023-10-16

我正在编写一个从命令行获取输入文件的函数。输入文件如下所示:

11 25
1 2 3 4 5 6 7 8
1 2 3
1 3 5
1 2 2

我想将第一行上的两个数字存储在整数变量中。第二行存储在数组中。第三行和后续行存储在另一个容器中。目前我有一个可以从第一行读取的程序:

void classFunctions::storeInput(const char* inputFile)
{
  std::ifstream file(inputFile);
  std::string placeholderString;
  while(!file.eof())
  {
    while(std::getline(file, placeholderString))
    {
     //Do something
    }
  }
}

但是我将如何更改它,以便它可以从第二、第三和后续行读取?

检查文本文件是否为空后,您应该调用getline()两次并继续阅读直到eof()

getline(file, first_line);
//proceed to process with a stringstream
getline(file, second_line);
//process
while(true) {
    string line;
    getline(file, line);
    //process
    if(file.eof()) break;
}

第一行只是对两个变量的提取。对于第二行,应该使用 std::getline(),您可能应该使用它std::istringstream并使用 std::istream_iterator 将行解析为数组。其余线路也需要连续调用std::getline()