简体   繁体   中英

fill right side of stringstream variable with '0' c++

I have the next code:

ofstream dataIndex;
dataIndex.open("file");

index="2222";
std::stringstream sstr1;
sstr1<<index<<'1';
sstr1<<setfill('0')<<setw(index.length()-9);
string index1= sstr1.str();
dataIndex<<index1;

dataIndex.close()

and i hope the result:

2222100000

but only i get

22221

without zeros? what happened?

Use std::left to left justify the output

#include <iostream>
#include <string>
#include <iomanip>

int main() 
{
  std::string s( "2222" );

  std::cout << std::setw(9) 
            << std::setfill('0') 
            << std::left 
            << s 
            << std::endl;
}

Output:

222200000

manipulators are applied to the stream the same as input. For them to take effect they need to be applied first. For example here is how you would fill zeros on a string stream.

std::string index("2222");
std::ostringstream sstr1;
sstr1 << std::setw(9) << std::setfill('0') << index << '1';
std::cout << sstr1.str(); // 0000022221

If you want to fill differently then simply add in a direction manipulator like std::left , std::right , etc.

std::string index("2222");
std::ostringstream sstr1;
sstr1 << index << std::setw(10-index.length()) << std::setfill('0') << std::left << '1';
std::cout << sstr1.str(); // 2222100000

Your setw() manipulator is invoked with a negative number (the length of Index string is just 4). That might be the culprit.

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