gpt4 book ai didi

c++ - 遍历文件直到 *string* 然后读取列直到 *no decimal*

转载 作者:太空狗 更新时间:2023-10-29 21:18:08 26 4
gpt4 key购买 nike

我有一个文件看起来像

some header
this is the first block
1 2 3 4
5 6 7 8
9 10 11 12
this is the second block
1 4 7 10
2 5 8 11
3 6 9 12
this is the third block
1 2 3 4
5 6 7 8
9 10 11 12

我想读取此文件并检查单词“first”、“second”和“third”,以便将以下数字 block 读入数组,以便稍后绘制它们。例如,我只想读取第二个 block 的第 1 列和第 2 列。主要问题是在第三个 block 开始之前我无法完成读入。它在秒 block 的第一行之后停止读取。简单来说,我的代码如下所示:

#include <string>
#include <fstream>
#include <istream>
#include <vector>

std::string line;
std::vector<double> vector1;
std::vector<double> vector2;
double v1;
double v2;
double v3;
double v4;

ifstream infile ("myfile.txt");
while (std::getline(infile, line)){
if (line.find("second",0) != std::string::npos){ // when "second" is found start to read block.
while (line.find_first_of("123456789.") != std::string::npos){ // while the next line is not a number continue reading. THIS DOESN'T WORK !
infile >> v1 >> v2 >> v3 >> v4;
vector1.push_back(v1);
vector2.push_back(v2);
std::getline(infile, line);
}
}
}
infile.close();

cout << "Vector1" << " " << "Vector2" << endl;
for (unsigned int i = 0; i < vector1.size(); i++){
cout << vector1[i] << " " << vector2[i] << endl;
}

预期的结果是:

Vector1  Vector2
1 4
2 5
3 6

但是我得到:

Vector1  Vector2
1 4

最佳答案

这应该修复双重读取内部并退出循环,

ifstream infile ("myfile.txt");
while (std::getline(infile, line)) {
if (line.find("second",0) != std::string::npos) {
while (infile >> v1 >> v2 >> v3 >> v4) {
vector1.push_back(v1);
vector2.push_back(v2);
// note getline is removed, else double reads on break.
}
// this may be needed if you plan on reading anything else.
infile.clear();
}
}

关于c++ - 遍历文件直到 *string* 然后读取列直到 *no decimal*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30872062/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com