2014-10-05 73 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()将行插入到矢量中,然后您将自己的行数与数量一起。

相关问题