【问题标题】:Read .txt file and put each line into vectors读取 .txt 文件并将每一行放入向量中
【发布时间】:2018-03-27 01:17:27
【问题描述】:

我很难弄清楚这将如何工作

我的指示如下: 文件中的一行(作为字符串输入)进入一个字符串向量。因此,如果文件有 25 行,那么(在输入之后)您最终会得到 25 个字符串向量,每个向量包含一个字符串。然后你开始将成对的向量连接成更大的向量,直到只有一个向量包含所有字符串。 我的问题是我将如何读取文件并为其拥有的每一行创建一个向量,因为该数字总是不同的?

【问题讨论】:

标签: c++ string class vector


【解决方案1】:

您应该创建一个向量的向量。这样,您可以使用索引来引用每个单独的向量。

How do you create vectors with different names in a for loop

【讨论】:

    【解决方案2】:

    由于向量是动态的并且不需要像数组那样具有固定大小,您可以简单地创建一个向量向量来存储文件的所有行。如果您的文件有 25 行,那么将有一个包含 25 个字符串向量的向量。请参阅下面的示例代码。

    #include <iostream>
    #include <vector>
    #include <fstream>
    using namespace std;
    
    /*
    There is a file (sample.txt) created for this example that contains the following contents:
    
    hello world
    this is a long line of words
    while
    this
    is
    a
    short
    line
    of
    words
    
    */
    
    int main(int argc, char*argv[])
    {
        ifstream file_To_Read(argv[1]);            //Creating an ifstream that opens a file from a command line argument
    
        vector< vector<string> > complete_Vector;  //This is a single vector that will contain multiple vectors
    
        string line;                               //String used to store file contents a line at a time
        vector<string> tempVec;                    //Vector that will contain the singular line
        while(getline(file_To_Read, line))         //While you can read the file's content a line at a time, place its content into line
        {
            tempVec.push_back(line);
            complete_Vector.push_back(tempVec);
        }
    
        //The sample file has 10 lines, so complete_Vector.size() should be 10 (10 vectors are in it)
          return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 2012-01-11
      • 2015-06-08
      • 1970-01-01
      • 2012-12-28
      • 1970-01-01
      • 2019-03-17
      相关资源
      最近更新 更多