简体   繁体   English

使用向量将文本文件中的输入存储到二维数组中

[英]storing input from text file into 2d array using vectors

So, I need to store the data from the text file into 2d array.所以,我需要将文本文件中的数据存储到二维数组中。 I tried using vectors.我尝试使用向量。 So here is the sample data from the text file:所以这里是来自文本文件的示例数据:

START  13
PID   11 
CORE 120
SSD 0
CORE 60
SSD 0
CORE 20
SSD 0

I want to store this data as final_vec[x][y].我想将此数据存储为 final_vec[x][y]。 This is what I tried:这是我尝试过的:

void read_file(const string &fname) {
    ifstream in_file(fname);
    string line;
    vector<string> temp_vec;
    vector<vector<string>> final_vec;

    while ( getline (in_file,line) )
    {
        stringstream ss(line);
        string value;
        while(ss >> value)
        {
            temp_vec.push_back(value);
        }
        final_vec.push_back(temp_vec);
    }

    for (int i = 0; i < final_vec.size(); i++) { 
        for (int j = 0; j < final_vec[i].size(); j++) 
            cout << final_vec[i][j] << " "; 
                cout << endl; 
    } 

}

int main()
{
    read_file("test.txt");
    return 0;
}

I get error:我得到错误:

main.cpp: In function ‘void read_file(const string&)’:
main.cpp:29:29: error: variable ‘std::stringstream ss’ has initializer but incomplete type
         stringstream ss(line);

I am not sure if I am on the right track.我不确定我是否在正确的轨道上。

IMHO, a better solution is to model each line as a record, with a struct or class :恕我直言,更好的解决方案是将每一行建模为一个记录,带有一个structclass

struct Record
{
  std::string label;
  int         number;

  friend std::istream& operator>>(std::istream& input, Record& r);
};

std::istream& operator>>(std::istream& input, Record& r)
{
    input >> r.label;
    input >> r.number;
    return input;
}

The overloaded operator>> makes the input loop a lot simpler:重载operator>>使输入循环更简单:

std::vector<Record> database;
Record r;
while (infile >> r)
{
    database.push_back(r);
}

Rather than have a 2d vector of two different types, the above code uses a 1D vector of structures.上面的代码没有使用两种不同类型的二维向量,而是使用一维结构向量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM