2012-12-23 51 views
1

我正在拼圖加載我的引擎中的bug,最後我發現它。然而,它似乎是錯誤的stringstream和getline ...最小的代碼:非常奇怪的stringstream和std :: getline行爲

#include <string> 
#include <iostream> 
#include <sstream> 

int main(int argc, char **argv) 
{ 
    std::string text = "1!2!6|6|5|"; 
    std::stringstream buffer; 
    buffer << text; // insert to buffer 

    std::string temp; 
    buffer >> temp; // extract 
    buffer << temp; // then insert again (i need it in my code to count characters) 
    // and I can't count it before, as in my code the buffer is filled from file 

    std::string loaded; 
    std::getline(buffer, loaded, '!'); //should instert "1" to loaded 
    std::cout << loaded; //and it displays nothing, debugger shows loaded is empty 
} 

我做錯了什麼或它是一個錯誤?我正在使用g ++ 4.7 C++ 11。

回答

4

對於在這種情況下,從字符串流中提取的字符串,你可能想:

temp = buffer.str(); 

代替:

buffer >> temp; 

參見:extracting formatted (interpreted) datastringstream.str()

+0

它的工作原理!非常感謝。只要有可能,我會接受你的答案。 – user1873947

+0

@ user1873947很高興幫助=) –