2013-04-28 69 views
1

我有如下功能:讀線,結尾沒有「 r」字符

void process (std::string str) 
{ 
    std::istringstream istream(str); 
    std::string line; 
    std::string specialStr("; -------- Special --------------------\r"); // win 
    //std::string specialStr("; -------- Special --------------------"); //linux 
    while (getline(istream,line)) 
    { 
     if (strcmp(specialStr.c_str(), line.c_str()) != 0) 
     { 
      continue; 
     } 
     else 
     { 
     //special processing 
     } 
    } 
} 

我讀通過線的std :: istringstream行線,採用getline,直到我「見面「特殊字符串 之後我應該爲下一行做一些特殊處理。 特殊字符串是:

; -------- Special -------------------- 當我在閱讀窗口的相應行線將其與 '\ r' 端:

; -------- Special --------------------\r) 在Linux中沒有 '\ R' 出現在末尾。 有沒有一種方法可以一致地讀取這些行,而無需區分它是linux還是windows?

感謝

+0

你是否可能以二進制模式打開了流? – jrok 2013-04-28 13:29:48

+0

std :: string str; //是一個參數std :: istringstream isaStream(str); //這樣我打開stringstream – Yakov 2013-04-28 13:31:50

+1

你從哪裏得到'str'的​​內容? (你可以張貼一些代碼,你懂的) – jrok 2013-04-28 13:33:06

回答

1

您可以使用此代碼,請從結束的 '\ r':

if(line[line.length() - 1] == '\r') line = line.substr(0, line.length() - 1); 

可以包裝成一個功能,這一點,如果你想:

std::istream& univGetline(std::istream& stream, std::string& line) 
{ 
    std::getline(stream, line); 
    if(line[line.length() - 1] == '\r') line = line.substr(0, line.length() - 1); 
    return stream; 
} 

融入你的函數:

void process (std::string str) 
{ 
    std::istringstream istream(str); 
    std::string line; 
    std::string specialStr("; -------- Special --------------------"); 

    while (univGetline(istream,line)) 
    { 
     if (strcmp(specialStr.c_str(), line.c_str()) != 0) 
     { 
      continue; 
     } 
     else 
     { 
     //special processing 
     } 
    } 
} 
+0

- 這是可以做到的 - 謝謝。但我更願意調用一些內置函數來擺脫/忽略'\ r'char – Yakov 2013-04-28 13:46:16

+0

您可以將代碼封裝在一個函數中。編輯。 – Scintillo 2013-04-28 13:53:24