2017-08-08 105 views
1

我看了其他的例子,但我不能讓這一個工作。 我有一個文件,在某些時候有奇怪的字符,例如:「Äèî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,不能繼續前進! 它可能是一些回車丟失?我正在用盡想法。

+0

值得投資一些時間與調試搞清楚到底出了什麼嬉戲的「Äèîpg」 。它可能是一個多字符編碼,任何這些字符都可能包含文件標記的末尾,或者出於某種原因導致流處於錯誤狀態。 – user4581301

+0

你好,事實上,這發生在我的txt文件。我的工作是跳過上一行中由「key = 0」引導的任何行。 – user6812514

+0

'if(lineNumber> = line1 - 20 && lineNumber <= 2)'更容易閱讀。額外的括號令人分心。要弄清楚他們沒有任何意義,需要時間。 –

回答

1

所以它看起來像你試圖拋棄行「鍵= 0」和下一行?

如果是這樣你可以在嵌套if語句來這樣使用ignoref.ignore(numeric_limits<std::streamsize>::max(), '\n')

如果lineNumber應該考慮這一行,你也將需要添加++lineNumber

如果這可能是在文件應在總添加此代碼的最後一行:

if(!f.ignore(numeric_limits<std::streamsize>::max(), '\n')) { 
    break; 
} 
++lineNumber; 

Live Example

+0

謝謝你的回覆。我很想念這裏的一些東西。你的意思是這樣嗎? (pos! if(pos!= string :: npos){ \t \t \t \t \t std :: cout <<「skip the line」<< endl; \t \t \t \t \t如果(函數getline(F,線)){ \t \t \t \t \t \t ++ LINENUMBER; \t \t \t \t \t} \t \t \t \t \t其他{ \t \t \t \t \t \t休息; \t \t \t \t \t} \t \t \t \t \t \t} 它不會爲我工作。我認爲while(getline(f,line)){創建一個問題。你能不能發表你的意思是代碼?我現在打印0個元素。 – user6812514

+0

謝謝你,但仍然無法正常工作。它發現第二次這些字符 – user6812514

+1

後,它可能會崩潰這可能是您的代碼中的其他錯誤。你的調試器應該有幫助。 – drescherjm