vector怎么从txt读取类的数据
时间: 2023-12-08 18:05:59 浏览: 32
假设你的txt文件中每行都是一个类对象的数据,例如:
```
1 a 10.2
2 b 20.5
3 c 30.1
```
其中每一行数据表示一个类对象,包含一个int类型的id,一个string类型的name和一个double类型的value。你可以按照以下步骤来读取并存储这些数据:
1. 定义一个类,用来存储一行数据:
```c++
class MyClass {
public:
int id;
string name;
double value;
};
```
2. 定义一个vector,用来存储所有的类对象:
```c++
vector<MyClass> myObjects;
```
3. 打开txt文件并逐行读取数据:
```c++
ifstream infile("data.txt");
string line;
while (getline(infile, line)) {
stringstream ss(line);
MyClass obj;
ss >> obj.id >> obj.name >> obj.value; // 从字符串中读取数据
myObjects.push_back(obj); // 将读取到的类对象存储到vector中
}
```
4. 关闭文件:
```c++
infile.close();
```
这样,你就可以从txt文件中读取类对象数据并存储到vector中了。
相关问题
c++从txt读取数据到vector
可以使用 ifstream 类读取 C++ 的文本文件,并使用 push_back 函数将数据存储到 vector 中。具体实现方法如下:
1. 包含头文件 fstream 和 vector
```
#include <fstream>
#include <vector>
```
2. 声明 ifstream 对象和 vector 对象
```
ifstream input_file("filename.txt"); // 替换为实际文件名
vector<int> data_vec;
```
3. 读取文件内容并存储到 vector 中
```
int num;
while (input_file >> num) { // 每次读取一个数字
data_vec.push_back(num); // 将数字存储到 vector 中
}
```
4. 关闭文件流
```
input_file.close();
```
最终,vector 对象 data_vec 中存储了文本文件中所有的数字。
c++从txt读取数据到二维vector
下面是一个示例代码,可以读取一个txt文件中的数据并将其保存到一个二维vector中:
```c++
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
ifstream in("data.txt"); // 打开文件
vector<vector<double>> data; // 定义二维vector
string line;
while (getline(in, line)) // 逐行读取文件内容
{
vector<double> row; // 定义一行数据的vector
double value;
stringstream ss(line); // 将字符串转换为stringstream
while (ss >> value) // 逐个读取每个数据
{
row.push_back(value); // 将数据添加到一行中
}
data.push_back(row); // 将一行数据添加到二维vector中
}
// 输出二维vector中的数据
for (auto& row : data)
{
for (auto& value : row)
{
cout << value << " ";
}
cout << endl;
}
return 0;
}
```
假设data.txt文件中有以下内容:
```
1.1 2.2 3.3
4.4 5.5 6.6
7.7 8.8 9.9
```
运行上述代码后,输出结果为:
```
1.1 2.2 3.3
4.4 5.5 6.6
7.7 8.8 9.9
```
可以看到,二维vector中成功保存了从txt文件中读取的数据。