使用矢量将文本文件中的输入存储到 2D 数组中
storing input from text file into 2d array using vectors
因此,我需要将文本文件中的数据存储到2d数组中。我尝试使用矢量。因此,以下是文本文件中的示例数据:
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);
我不确定我是否走在正确的轨道上。
恕我直言,更好的解决方案是将每行建模为记录,并带有struct
或class
:
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);
}
上面的代码没有两种不同类型的 2D 向量,而是使用结构的一维向量。
相关文章:
- 使用矢量将文本文件中的输入存储到 2D 数组中
- 创建一个数组,以允许用户输入存储并稍后在代码中使用
- 如何将用户输入存储在数组中?
- 如何将控制台的输入存储到 wchar_t 变量?
- 是否可以将来自 Win32 EDIT 控件的文本输入存储在C++ std::string 中?
- 如何使用指针将用户输入存储到向量中
- 更改GTK ::输入存储在特定变量中的颜色
- 使用 Getline C++ 将每一行输入存储在数组中
- 根据用户输入存储多个数组
- 如何将用户输入存储在变量中,该变量与默认构造函数中的变量初始化中的值不同
- 将多个输入存储到数组中
- 如何将多个输入存储到列表C++中
- 将用户输入存储到2D数组中时要覆盖的值
- 如何将用户字符串输入存储在数组中,C++
- 将输入存储到数组C++中
- 努力创建一个函数,将用户输入存储到任意选择的向量(使用c++)
- 是否有可能在每次while循环迭代后将用户输入存储在一个新变量中?
- 如何将用户输入存储到多维数组中?我正在使用 3D 阵列
- 用户输入存储在整型数组中的值c++
- 关于将输入存储到字符串中,并使用cout来显示它