2014-10-05 14 views
-2

我必須製作此程序,我必須從文本文件中獲取行,然後僅打印文件的最後十行。如果文本文件中的行數小於10,則打印出整個文件。到目前爲止,我有這個代碼。我被困在如何將行存儲在向量或數組中。將行存儲在C++中的向量中

#include <iostream> 
#include <fstream> 
#include <string> 
#include <vector> 

using namespace std; 

int main() 
{ 
    fstream file; 
    string filename; 
    vector <string> filelines(100); 
    string line; 
    cout << "Enter the name of the file you wish to open. "; 
    cin >> filename; 

    //open the file. 
    file.open(filename.c_str(), ios::in); 
    if (file) 
    { 
     cout << "File opened successfully." << endl; 
     int index = 0; 
     while (getline(file,line)) 
     { 
      cout << line << endl; 
     } 


    } 
    else 
    { 
     cout << "File failed to open" << endl; 
    } 



    return 0; 
} 

my sample text file looks like this 
This is line 0 
This is line 1 
This is line 2 
This is line 3 
This is line 4 
This is line 5 
This is line 6 
This is line 7 
This is line 8 
This is line 9 
This is line 10 
This is line 11 
This is line 12 
This is line 13 
This is line 14 
This is line 15 
This is line 16 
This is line 17 
This is line 18 
This is line 19 
This is line 20 
This is line 21 
This is line 22 
This is line 23 
This is line 24 
This is line 25 
This is line 26 
This is line 27 
This is line 28 
This is line 29 
This is line 30 
This is line 31 
This is line 32 
This is line 33 
This is line 34 
+1

不要預先將矢量大小設置爲任意數量的字符串。創建它爲空並使用'while(getline(file,line)){filelines.push_back(line); }'。或者,掃描整個文件,計算行數並記住最後10行的位置。這會在讀取大文件時節省內存。 – 2014-10-05 13:49:54

+0

當我輸入你給我的這條線時,它告訴我「文件行必須有一個類的類型。」我在矢量聲明語句中刪除了100。 錯誤C2228:左 '.push_back' 必須具有類/結構/聯合 而(函數getline(文件,線)) \t \t { \t \t \t COUT <<線<< ENDL; \t \t \t filelines.push_back(line); \t \t} – Koolkirtzz 2014-10-05 13:53:14

+0

使用'vector filelines;'as'vector filelines();'定義了一個不帶參數並返回一個字符串向量的函數。歡迎來到C++ – 2014-10-05 13:55:53

回答

0

我被困在如何存儲在向量或數組中的行,因爲我需要的東西,是類似於Java ArrayList中一息尚存,我不知道究竟有多少行會在那裏的文本文件。

由於您使用的是std::vector您不需要知道文件中有多少行以插入它們。該向量將通過增加其內部數組來容納要插入的元素。使用push_back()將行插入到矢量中,然後您將自己的行數與數量一起。

相關問題