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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With