我有一個文件看起來像通過文件,直到*串運行*,然後讀取列,直到*沒有小數*
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
我想讀這個文件並檢查單詞「第一」,「第二」和「第三」,以便將以下數字塊讀入數組,以便稍後繪製它們。例如,我只想讀第二塊的柱1和2。主要的問題是,我不能完成閱讀,直到第三塊開始。它在秒塊的第一行之後停止讀取。在一個簡單的方法我的代碼看起來是這樣的。:
#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
我讀了清楚的文檔,但是這對它有什麼好處? – uitty400
使用'operator >>'進行輸入時,如果發生故障,則會設置錯誤,並且必須先清除才能再次使用。如果你只加載一個塊,這不是問題,但是如果在同一個循環中你也掃描「第一」和「第三」,你需要在讀取下一個塊之前清除。 –