【问题标题】:Storing lines in a vector in c++在c ++中将行存储在向量中
【发布时间】:2014-10-05 13:47:25
【问题描述】:

我必须制作这个程序,我必须从文本文件中获取行,然后只打印出文件的最后十行。如果文本文件中的行数少于 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

【问题讨论】:

  • 不要将向量的大小预先设置为任意数量的字符串。将其创建为空并使用while (getline(file,line)) { filelines.push_back(line); }。或者,扫描整个文件,计算行数并记住最后 10 行的位置。这将在读取大文件时节省内存。
  • 当我输入你给我的那一行时,它告诉我“文件行必须有一个类类型。”我删除了向量声明语句中的 100 。错误 C2228:'.push_back' 左侧必须有类/结构/联合 while (getline(file,line)) { cout
  • 使用vector &lt;string&gt; filelines; as vector &lt;string&gt; filelines(); 定义了一个不带参数并返回字符串向量的函数。欢迎使用 C++
  • 好的。我在向量的声明中有一个小的语法错误。太感谢了。 :)

标签: c++ file-io vector


【解决方案1】:

我被困在如何将行存储在向量或数组中,因为我需要类似于 Java 中的 arraylist 的东西,因此我不知道文本文件中有多少行。

由于您使用的是std::vector,因此您无需知道文件中有多少行即可插入它们。该向量将通过增长其内部数组来容纳您要插入的元素。使用push_back() 将线条插入向量中,然后您将拥有线条本身以及数量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    相关资源
    最近更新 更多