簡體   English   中英

從文件中讀取或顯示特定行

[英]read or display specific line from text a file

例如,文件有 100 行,我只想顯示 20 行並要求用戶按 Enter 鍵,然后再顯示 20 行,依此類推到文件末尾。

這是我的代碼

    int main()
    {
     ifstream infile;
      string filename;
      string line;
      int lineCount = 0;

      cout << "Enter file name: \n";
      cin >> filename;

      system("cls");

      infile.open(filename);


      if (!infile) 
      {
       cout << "\nErrors\nNo file exist.\n";
        exit(1);
      }
      else 
      {

       while (infile.good())
       {
        lineCount++;

         getline(infile, line);

         cout << lineCount << ":\t" << line << endl;
       } 
      }
      return 0; 
      }

你只需要數線。 例子:

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

int main()
{
    ifstream infile;
    string filename;
    string line;
    int lineCount = 0;

    cout << "Enter file name: \n";
    cin >> filename;

    system("cls");

    infile.open(filename);


    if (!infile)
    {
        cout << "\nErrors\nNo file exist.\n";
        exit(1);
    }
    else
    {

        while (getline(infile, line))
        {


            cout << lineCount << ":\t" << line << endl;

            if (lineCount % 20 == 0) {
                cout << "Press Enter To Read 20 More Lines, Or Type Quit to Exit";
                string response;
                getline(cin, response);
                if (response == "Quit") return 0;

            }
            lineCount++;
        }
    }
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM