簡體   English   中英

如何從頭到尾讀取文本文件。 C++

[英]How to read a text file from the beginning up to a certain point. C++

所以我正在為討論隨機訪問文件的 class 做一些工作。 其中一個問題(選項 3)要求我們創建一個代碼,該代碼獲取一個文本文件,並從頭到尾讀取並顯示其內容(這將由用戶給出)。 在該用戶給出輸入后,我如何能夠將代碼設置為停止閱讀? 到目前為止,這是我的代碼

#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
#include <iomanip>

using namespace std;

int main() {
  char filename[]="file.txt"; 
  char content[10];
  ifstream inFile;
  int choice;
  int option;
  l1: cout << "Choose an option to decide what you want to do with the file." << endl;
  cout << "Option 1: Beginning to End."<< endl;
  cout << "Option 2: End to Beginning."<< endl;
  cout << "Option 3: Beginning to Certain Point."<< endl;
  cout << "Option 4: Certain Point to Certain Point. "<< endl;
  cin >> choice;

  if (choice==1){

  inFile.open(filename);
  if(inFile.fail())
    {
         cout << "file named can not be found \n";
         system("pause");
         exit(1);
    }
    inFile>>content;
    while(inFile.good()) 
    {
     cout <<content<< ' ' <<endl;
     inFile>>content;
     }
        inFile.close();

    cout << "Do you want to go again? 1 for Yes and 2 for No."<< endl;
    cin >> option;
    if (option== 1)
    {
      goto l1;
    }
    else
    {
      terminate();
    }
  }

  if (choice==2){

    inFile.open(filename);
    if(inFile.fail())
    {
         cout << "file named can not be found \n";
         system("pause");
         exit(1);
    }

    char c;
    std::ifstream myFile(filename,std::ios::ate);
    std::streampos size = myFile.tellg();
    for(int i=1;i<=size;i++){
        myFile.seekg(-i,std::ios::end);
        myFile.get(c);
        printf("%c",c);
    }
    cout << "Do you want to go again? 1 for Yes and 2 for No."<< endl;
    cin >> option;
    if (option== 1)
    {
      goto l1;
    }
    else
    {
      terminate();
    }
  }

  if (choice==3){

    inFile.open(filename);
    if(inFile.fail())
        {
         cout << "file named can not be found \n";
         system("pause");
         exit(1);
        }







  }


  }

最簡單的方法是輸入他們想要停止讀取的字符或行號並計數到該值。 就像是

int amount_read = 0;
int amount_to_be_read;
cin >> amount_to_be_read;

inFile>>content;
while(inFile.good() && amount_read < amount_to_be_read) 
{
    cout <<content<< ' ' <<endl;
    inFile>>content;
    amount_read++;
}
inFile.close();

暫無
暫無

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

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