【问题标题】:Having trouble figuring out this issue I'm having with getline() for file IO无法解决这个问题,我在使用 getline() 进行文件 IO 时遇到了问题
【发布时间】:2022-11-19 10:42:31
【问题描述】:

所以我试图打开一个文件,一次显示 20 行直到文件结束,然后关闭程序。真的很容易。这是代码:

int main()
{
    using namespace std;

    //try catch block sets up exception handling for files that do not exist. I added a few different
    //text files to search for
    try {
        //intro message and prompt for file name
        cout << "Welcome to the Advanced File I/O program." << endl;
        cout << "Please enter the name of the text file you would like to search for: ";
        string input;
        cin >> input;
        //concatonate input with .txt file designation
        string fileName = input + ".txt";
        fstream myFile;
        //open the file and read it in
        myFile.open(fileName, ios::in);
        //if the file exists
        if (myFile.is_open()) {
            string line;
            //while there are lines to be read in
            while (getline(myFile, line)) {
                
                //display 20 at a time
                for (int i = 0; i < 20 && getline(myFile, line); i++) {
                    cout << line << endl;
                }
                //app console controle
                system("pause");
                system("cls");
            }
            //app console controle
            system("pause");
            system("cls");
            //close the file once it's all read in and display end message
            myFile.close();
            system("cls");
            cout << "You have reached the end of the text file. " << endl;
            cout << "Thank you for visiting! Goodbye!" << endl;
            system("pause");
            exit(0);


        }
        //if the file does not open (does not exist) throw the error exception and close the program
        else if (myFile.fail()) {
            throw exception("File does not exist. Closing Program.");
            cout << endl;
            system("cls");
            exit(0);
        }
    }
    //catch the exception and display the message
    catch (exception& e) {
        cout << "\nError caught!" << endl;
        cout << e.what();
    }

}

问题是它每次在 for 循环中都跳过输出的第一行。我很确定会发生这种情况,因为我调用了 getline() 两次。但是,我不知道如何解决这个问题。任何提示将不胜感激。

对于那些要告诉我不要使用 namespacestd 的人;我必须参加此作业所在的课程。

谢谢!

【问题讨论】:

  • 另外澄清一下:当我运行程序时,它正在运行第 2-21 行... 23-42... 44-63 等等
  • 看到了吗getline(myFile, line)两次在你的程序中?你在每一个之后打印line吗?
  • 那是有史以来最简单的修复方法。现在我觉得很蠢。谢谢你大声笑。

标签: c++ file-io getline


【解决方案1】:

我只需要在 while 循环中初始 getline() 调用之后打印该行。

【讨论】:

  • 您需要进行更多更改才能实现“一次 20 行”
猜你喜欢
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
  • 2021-11-02
  • 1970-01-01
  • 2023-03-20
  • 2020-11-27
  • 2018-12-22
  • 2021-12-08
相关资源
最近更新 更多