Search code examples
file-ioload-data-infile

How to skip a line from an infile


I have this code that allows the user to load an input file (option 1), display the contents of the input file (option2) and they have the option to exit (option 3). Is there any way that I can skip the first line of the input file from being couted?

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

 }

Solution

  • Just continue inside the while loop. This will re-trigger the getLine function, which will move the pointer forward 1 line.

    while (getline(file, line))
    {
        if ( skipLineCondition ) { continue; }
    
        cout<<line<<"\n";
    }
    

    Also, please try to post better formatted code. We are here to help, but you should focus more effort into making it easy for everyone to help you.