c++导入txt文件中的数据
时间: 2024-03-17 16:41:21 浏览: 110
以下是在 C++ 中导入 txt 文件数据的示例代码:
```c++
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main() {
// 创建一个 vector 用于存储 txt 文件中的数据
vector<string> data;
// 打开 txt 文件
ifstream file("data.txt");
// 逐行读取文件中的数据
string line;
while (getline(file, line)) {
// 将读取到的每一行数据添加到 vector 中
data.push_back(line);
}
// 关闭文件
file.close();
// 输出读取到的数据
for (int i = 0; i < data.size(); i++) {
cout << data[i] << endl;
}
return 0;
}
```
该代码将读取名为 "data.txt" 的 txt 文件中的数据,并将每一行数据添加到一个 vector 中。最后将 vector 中的数据逐行输出。
需要注意的是,如果 txt 文件中的每行数据类型不同,例如一行是整数,一行是字符串,需要对读取到的数据进行类型转换。
阅读全文
相关推荐
















