文件内容读取出到vector
时间: 2023-08-08 09:13:20 浏览: 58
可以使用C++标准库中的fstream和vector来实现。
假设我们有一个文件"data.txt",其中包含一些数据,每个数据占据一行。我们可以使用以下代码将文件内容读取到一个vector中:
```cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
int main() {
std::ifstream fin("data.txt");
std::vector<std::string> data;
std::string line;
while (std::getline(fin, line)) {
data.push_back(line);
}
fin.close();
// 输出读取的数据
for (const auto& s : data) {
std::cout << s << std::endl;
}
return 0;
}
```
上述代码中,首先我们使用`std::ifstream`打开文件"data.txt",然后定义一个vector`data`来存储读取的数据。接下来使用`std::getline`函数从文件中读取一行数据,并将其存储到`line`中。如果读取成功,则将`line`添加到`data`中。最后关闭文件流。
需要注意的是,`std::getline`函数会读取文件中的空行,如果不希望将空行作为数据存储到vector中,可以添加如下判断:
```cpp
while (std::getline(fin, line)) {
if (!line.empty()) { // 判断line是否为空
data.push_back(line);
}
}
```
另外,如果文件中的每行数据都是数值类型,可以使用`std::stoi`、`std::stof`等函数将字符串转换为相应的数值类型。例如:
```cpp
std::vector<int> numbers;
std::string line;
while (std::getline(fin, line)) {
if (!line.empty()) {
numbers.push_back(std::stoi(line));
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)