在c ++中存储向量中的行

时间:2014-10-05 13:47:26

标签: c++ file-io vector

我必须制作这个程序,我必须从文本文件中获取行,然后只打印出文件的最后十行。如果文本文件中的行小于10,则打印出整个文件。到目前为止,我有这个代码。我被困在如何将线存储在矢量或数组中。

#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 个答案:

答案 0 :(得分:0)

  

我坚持如何将行存储在向量或数组中,因为我需要类似于Java中的arraylist的东西,因此我不确切知道文本文件中有多少行。< / p>

由于您正在使用std::vector,因此您无需知道文件中有多少行就可以插入它们。向量将通过增长其内部数组来容纳要插入的元素。使用push_back()将线条插入向量中,然后将线条与金额一起使用。