【问题标题】:How to skip a line from an infile如何从 infile 中跳过一行
【发布时间】:2019-09-21 08:21:39
【问题描述】:

我有这段代码允许用户加载输入文件(选项 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;

 }

【问题讨论】:

    标签: file-io load-data-infile


    【解决方案1】:

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

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

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

    【讨论】:

    • 非常感谢您的帮助,是的,我会努力做得更好,我之前只在这里发过两次,所以我还在学习中,感谢您的帮助!
    • 我还需要更好地记录我的工作,下次我在这里发帖时一定会注意这一点:)
    • 没问题。我的回答对你有帮助吗?如果是这样,您可以将其标记为答案:)
    猜你喜欢
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 2020-06-26
    • 1970-01-01
    • 2018-08-20
    • 2019-04-04
    • 2013-01-12
    相关资源
    最近更新 更多