简体   繁体   中英

White space insertion in std::stringstream fails

I'm trying to insert white space in std::stringstream in this way.

std::stringstream sstr;
sstr.str("");
sstr << " ";
sstr << 10;

and then setting it as a label like that

label->setString(sstr.str().c_str());

but it's only giving me 10, space is not included. I've followed many links to solve problem but of no use. Following link suggests to use getline() but in my case I cannot do that :

stringstream doesn't accept white space?

I've also tried to use std::noskipws but it also not work :

sstr << std::noskipws << " ";

Any help will be appreciated.

std::stringstream should not remove your whitespace when used like this. Are you sure that it is not the label-object that is trimming your string and removing the whitespace?

Try debugging or printing out your string before setting it to the label.

You can use put method to append a single char:

std::stringstream sstr;
sstr.str("");
sstr.put(' ');
sstr.put(10);

I think you're using it wrong:

string labelstr;
std::stringstream sstr;
sstr.str("");
sstr << " ";
sstr << 10;
ss >> noskipws >> labelstr;
label->setString(labelstr);

http://www.cplusplus.com/reference/ios/noskipws/

Your code works as expected for me. Here's a runnable example: http://cpp.sh/8d6 .

The culprit must be setString trimming your input. Or possibly some other function that reads the string later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM