c++ - 如何跳过文本文件中的标题行并将其余数据读回主函数?

标签 c++

我只是在学习文本文件输入/输出。我输出了一个文件,其中包含一个标题和下面的 10 行数据。 我现在想把它读回主函数。如果我在文本文件中省略标题,这对我有用,但如果我保留标题,我会得到一个无限循环。 如何在读回此数据时跳过第一行(标题行),或者如果可能的话,读回标题和数据? 这是我目前所拥有的:

void fileRead(int x2[], double y2[], int& n, char filename)
{
     ifstream fin ("pendulum.txt"); // fin is an input file stream

     if(!fin) //same as fin.fail()
     {
              cerr << "Failure to open pendulum.txt for input" << endl;
              exit(1);
     }

     int j = 0, dummy = 0; //index of the first value j and dummy  value
     while(!fin.eof()) //loop while not end of file
     {
           fin >> dummy >> x2[j] >> y2[j];
           cout << setw(5) << fixed << j
                << setw(12) << scientific << x2[j] << "   "
                << setw(12) << y2[j] << endl; //print a copy on screen
           j += 1;           
     }

     fin.close(); //close the input file

}

最佳答案

您可以先读取文件头,然后读取您想要的真实内容如下:

string line;
getline(fin, line);//just skip the line contents if you do not want header
while (fin >> dummy >> x2[j] >> y2[j] )
{   //^^if you do not always have a dummy at the beginning of line
    //you can remove dummy when you read the rest of the file
   //do something
}

关于c++ - 如何跳过文本文件中的标题行并将其余数据读回主函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16068997/

相关文章:

C++:std::vector [] 运算符

c++ - 为什么 reference 不能捕获 temporary 而 const ref 和 rval ref 可以

c++ - 在独立于平台的设计中传递特定于平台的数据?

c++ - 在此示例中使用指针的好处?

c++ - SFML - 将对象移向坐标

c++ - 帮助解决错误 LNK2019 : unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup

c++ - 检查是否启用了 DWM/Aero,并让该代码存在于 2000/XP/Vista/7 的相同二进制文件中

c++ - 数组中的唯一整数

c++ - 加载一个 DLL,该 DLL 调用加载它的 DLL 中的函数

c++ - 从临时返回常量对象和构造