2013-10-01 67 views
0

我注意到一個奇怪的行爲,只是下面這個非常簡單的程序。使用「>>」運算符使用std :: istringstream的奇怪行爲

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

int main(void) 
{ 
    std::string data = "o BoxModel\nv 1.0f, 1.0f, 1.0f\nv 2.0f, 2.0f, 2.0f\n"; 
    std::istringstream iss(data); 
    std::string line; 
    std::string type; 

    while (std::getline(iss, line, '\n')) 
    { 
     iss >> type; 

     std::cout << type << std::endl; 
    } 
    getchar(); 
    return (0); 
} 

輸出如下:

v 
v 
v 

但我想下面的一個:

o 
v 
v 

我試過這個解決方案:

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

int main(void) 
{ 
    std::string data = "o BoxModel\nv 1.0f, 1.0f, 1.0f\nv 2.0f, 2.0f, 2.0f\n"; 
    std::istringstream iss(data); 
    std::string line; 
    std::string type; 

    iss >> type; 
    std::cout << type << std::endl; 

    while (std::getline(iss, line, '\n')) 
    { 
     iss >> type; 

     std::cout << type << std::endl; 
    } 
    getchar(); 
    return (0); 
} 

但輸出如下:

o 
v 
v 
v 

有人能幫助我嗎?提前感謝您的幫助。

+0

好像你試圖做*你* * *時(:。 – Rubens

回答

2

調用getline後,您將從字符串流的緩衝區中移除第一行。第一個換行符後的字符串中的單詞是「v」。

在你的while循環中,創建另一個stringstream作爲輸入。現在從這個stringstream中提取你的類型單詞。

while (std::getline(iss, line, '\n')) 
{ 
    std::istringstream iss2(line); 
    iss2 >> type; 

    std::cout << type << std::endl; 
} 
+0

非常感謝您的回答再見 – user1364743

+0

@ user1364743如果是回答你的問題,那麼請接受它在這裏,在StackOverflow上。我們不會說謝謝,我們讚揚和/或接受答案。 – Ali