【问题标题】:storing input from text file into 2d array using vectors使用向量将文本文件的输入存储到二维数组中
【发布时间】:2020-05-23 03:17:51
【问题描述】:

所以,我需要将文本文件中的数据存储到二维数组中。我尝试使用向量。所以这里是来自文本文件的示例数据:

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

我想将此数据存储为 final_vec[x][y]。这是我尝试过的:

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;
}

我得到错误:

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);

我不确定我是否走在正确的轨道上。

【问题讨论】:

标签: c++ vector


【解决方案1】:

恕我直言,更好的解决方案是将每一行建模为一条记录,使用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;
}

重载的operator&gt;&gt; 让输入循环变得简单了很多:

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

上面的代码没有使用两种不同类型的二维向量,而是使用结构的一维向量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多