簡體   English   中英

使用向量將文本文件中的輸入存儲到二維數組中

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

所以,我需要將文本文件中的數據存儲到二維數組中。 我嘗試使用向量。 所以這里是來自文本文件的示例數據:

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

我不確定我是否在正確的軌道上。

恕我直言,更好的解決方案是將每一行建模為一個記錄,帶有一個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>>使輸入循環更簡單:

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

上面的代碼沒有使用兩種不同類型的二維向量,而是使用一維結構向量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM