2013-06-05 136 views
4

我有以下代码:stringstream不接受空格?

std::stringstream ss; 
ss << 1 << "a b c"; 
std::string result; 
ss >> result; 
std::cout << result << std::endl; 

我看 “1A”,而不是 “1A B C”。

我在某处读到我应该有的东西< < std :: noskip。但它没有帮助。

有什么想法?

在此先感谢。

+0

使用'getline'代替。 –

回答

8
std::getline(ss, result); 

,或者只是得到string

result = ss.str(); 
+1

前段时间,我遇到了'std :: noskipws'问题,并且我没有找到足够清晰的文档,所以我会用'getline'去。 – Djon

+4

noskipws不会像你想象的那样影响字符串。 '1a'仍然会被读取而不是行。当流以空格开始时,差异就会出现。如果你输入'aa bb cc',那么没有'noskipws','aa'将被读取,用noskipws -empty字符串! –

+2

noskipws对于阅读单个字符很有用 –

0
//Try using this for getting whitespace in string 
    string input; 
    cout<<"\nInput : "<<input; 
    getline(cin,input); 
    string result,label; 
    std::stringstream sstr(input); 
    while(sstr>>label){ 
     result=result+label+" "; 
    } 
cout<<"\nResult : "<<result;