c++从txt读取数据到二维vector
时间: 2023-10-17 17:08:02 浏览: 89
下面是一个示例代码,可以读取一个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文件中读取的数据。