2013-09-26 135 views
1

所以我試圖從文件中讀入。如果在一條線的中間有一個'#',或者對於這個問題的任何地方,我想忽略其餘部分,並繼續閱讀。這是我有:'#'後忽略所有內容

while(getline(pgmFile, temp)) 
    { 
    istringstream readIn(temp); 
    lines++; 

    while(readIn >> convert) 
    { 
     //cout << temp[counter] << endl; 
     if (temp.length() == 0 || temp[counter] == '#' || temp[counter] == '\r' || temp[counter] == '\n') 
     {} 
     else 
     {/*cout << temp << endl;*/} 
     if(temp.at(counter) == '\n' || temp.at(counter) == '\r') 
     {} 
     if(convert < 57 || convert > 40) 
     { 
     pixels.push_back(convert); 

     } 
    } 

此輸入文件:

P5 
4 2 
64 

0 0 0 0 # don't read these: 1 1 1 1 
0 0 0 0 

應該在0的閱讀,但#後,什麼都沒有。

temp是「string」類型,它是逐行讀取的。

任何幫助非常感謝!

+0

這樣做:'temp.erase(標準::發現(temp.begin(),溫度.end(),'#'),temp.end())'在將你的行發送到字符串流之前。 – WhozCraig

+0

這個技巧。非常感謝! – Necrode

回答

2

在構建istringstream時,您可以在第一個'#'(如果存在)切割您的字符串。這將讓你假裝的'#'簡化你的邏輯的其餘部分從未有:

while(getline(pgmFile, temp)) 
    { 
    size_t pos = temp.find('#'); 
    istringstream readIn(pos == string::npos ? temp : temp.substr(0, pos)); 
    lines++; 
    ... 
    } 

既然你讀行由行,因爲分隔符被丟棄,那麼可以跳過對檢查'\n'人物也是:它不會在那裏。

+0

然後我不需要檢查'#'字符嗎? {} – Necrode

+0

@Necrode不,如果它在那裏,它會被'substr'刪除。 – dasblinkenlight

1

雙函數getline(一個爲線,一個用於忽略任何起始於 '#'):

#include <iostream> 
#include <sstream> 

int main() { 
    // Ignoring P5 
    std::istringstream pgmFile(std::string(
     "4 2\n" 
     "64\n" 
     "\n" 
     "0 0 0 0 # don't read these: 1 1 1 1\n" 
     "0 0 0 0\n")); 
    std::string line; 
    while(getline(pgmFile, line)) { 
     std::istringstream line_stream(line); 
     std::string line_data; 
     if(getline(line_stream, line_data, '#')) { 
      std::istringstream data_stream(line_data); 
      int pixel; 
      // Here I omitted additional error checks for simplicity. 
      while(data_stream >> pixel) { 
       std::cout << pixel << ' '; 
      } 
     } 
    } 
    std::cout << std::endl; 
    return 0; 
} 
相關問題