使用c++从execl中读取第11,12列的所有元素并输出
时间: 2024-02-19 19:59:02 浏览: 56
可以使用C++中的文件流和字符串流来读取execl中的数据。假设execl文件的分隔符为逗号,可以按照以下步骤进行操作:
1. 包含头文件
```c++
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include <vector>
```
2. 打开execl文件
```c++
std::ifstream file("example.csv");
if (!file.is_open()) {
std::cout << "Failed to open file!" << std::endl;
return 1;
}
```
3. 读取第11,12列的数据并输出
```c++
std::string line;
std::vector<std::string> col11, col12;
while (std::getline(file, line)) {
std::stringstream ss(line);
std::string cell;
int col_idx = 0;
while (std::getline(ss, cell, ',')) {
++col_idx;
if (col_idx == 11) {
col11.push_back(cell);
} else if (col_idx == 12) {
col12.push_back(cell);
}
}
}
for (int i = 0; i < col11.size(); ++i) {
std::cout << "Col 11: " << col11[i] << ", Col 12: " << col12[i] << std::endl;
}
```
完整代码如下:
```c++
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include <vector>
int main() {
std::ifstream file("example.csv");
if (!file.is_open()) {
std::cout << "Failed to open file!" << std::endl;
return 1;
}
std::string line;
std::vector<std::string> col11, col12;
while (std::getline(file, line)) {
std::stringstream ss(line);
std::string cell;
int col_idx = 0;
while (std::getline(ss, cell, ',')) {
++col_idx;
if (col_idx == 11) {
col11.push_back(cell);
} else if (col_idx == 12) {
col12.push_back(cell);
}
}
}
for (int i = 0; i < col11.size(); ++i) {
std::cout << "Col 11: " << col11[i] << ", Col 12: " << col12[i] << std::endl;
}
return 0;
}
```
阅读全文