如何从 infile 中跳过一行

How to skip a line from an infile

我有这段代码允许用户加载输入文件(选项 1)、显示输入文件的内容(选项 2)并且他们可以选择退出(选项 3)。有什么办法可以跳过输入文件的第一行吗?

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;

int main ()
{ char selection = ' ';
  char fileName[25];
  ifstream file;
  string line;

cout<< "Choose an action"<<endl;
string myMenu[3]={" 1 - Load An Exam ", " 2 - Display Exam ", " 3 - Quit " };
    for (int i=0; i<3; i++)
            {   cout<<myMenu[i]<<endl;}
            cin>>selection;

    switch(selection)   

{
    case '1': 
    cout<<"Please enter  the file name"<<endl;
    cin>>fileName,25;
    file.open(fileName);

    if (file.fail())
    {cout<<"Unable to open file"<<endl; 
     cout<<"Please enter the file name"<<endl;
    cin>>fileName,25;
    file.open(fileName); }



     break;

    case '2':
    if (file.good())
    { 
     while (getline(file, line))
    {cout<<line<<"\n";}
        file.close();
    }
    else cout<<"Unable to open file";
    break;   
    case '3':
        cout<<"Thank you!"<<endl;
    break;

 }

只需在 while 循环内继续。这将重新触发 getLine 函数,它将指针向前移动 1 行。

while (getline(file, line))
{
    if ( skipLineCondition ) { continue; }

    cout<<line<<"\n";
}

另外,请尝试post更好的格式化代码。我们随时为您提供帮助,但您应该更加努力让每个人都能轻松地为您提供帮助。