我看了其他的例子,但我不能讓這一個工作。 我有一個文件,在某些時候有奇怪的字符,例如:「Äèîpg」 我不想保存這一行,因爲它似乎與getline的循環將停止在那裏(它存儲,直到與垃圾的行)。我怎麼能這樣做?我知道發生這種情況時:「key = 0」,下一行將會有這些字符「Äèîpg」。如何跳過下一行如果條件C++
這裏是我的代碼:
file = "example.log";
ifstream f(file);
f.open(file);
if (f.good()){
while (getline(f, line)) {
lineNumber++;
if ((lineNumber>= line1 - 20) && (lineNumber<= line2)){
pos = line.find("key = 0");
if (pos != string::npos){
std::cout << "skip the line" << endl;
}
else{
Type v;
v.line= line;
v.index = lineNumber;
linesVector.push_back(v);
}
}
}
}
f.close();
然後我創建一個信息,我需要截除文件:
ofstream myfile;
string merge = file + "_Cut.log";
myfile.open(merge);
for (unsigned int i = 0; i < linesVector.size(); i++){
myfile << linesVector[i].line << "\n";
//std::cout << linesVector[i].line << endl;
}
myfile.close();
預先感謝您的幫助!
爲了清楚我的文件是怎麼樣的,在這裏它的原始「example.log」 (我不能附加到某處)。
2017-08-03 09:38:46 Expeum im6
2017-08-03 09:38:46 nubla4
2017-08-03 09:38:46 blaze
2017-08-03 09:38:46 ue
2017-08-03 09:38:46 er
2017-08-03 09:38:46 key = 0
2017-08-03 09:38:46 Q2žl2pE&ö³„Ôï¬ÈL+g…^cÎ1áø/7E›¸¥ü‰úLÎ’Æ
2017-08-03 09:38:46 81B9CEandrew499OEE4MUI5Q0VhbmRyZXc0OTk=
2017-08-03 09:38:47 B9CEandrew499OEE4MUI5Q0VhbmRyZXc0OTk=
2017-08-03 09:38:48 bla
2017-08-03 09:38:49 OK
2017-08-03 09:50:12 key = 0
2017-08-03 09:50:12 E&ö³„Ôï¬ÈL+g…^cÎ1áø/7E›¸¥ü‰úLÎ’Æ
,這裏是我在截除文件獲得:
2017-08-03 09:38:46 Expeum im6
2017-08-03 09:38:46 nubla4
2017-08-03 09:38:46 blaze
2017-08-03 09:38:46 ue
2017-08-03 09:38:46 er
2017-08-03 09:38:46 key = 0
2017-08-03 09:38:46 Q2žl2p
的問題是,它是停留在過去的giberrish,不能繼續前進! 它可能是一些回車丟失?我正在用盡想法。
值得投資一些時間與調試搞清楚到底出了什麼嬉戲的「Äèîpg」 。它可能是一個多字符編碼,任何這些字符都可能包含文件標記的末尾,或者出於某種原因導致流處於錯誤狀態。 – user4581301
你好,事實上,這發生在我的txt文件。我的工作是跳過上一行中由「key = 0」引導的任何行。 – user6812514
'if(lineNumber> = line1 - 20 && lineNumber <= 2)'更容易閱讀。額外的括號令人分心。要弄清楚他們沒有任何意義,需要時間。 –