Newbie question. How do I pad a std::string
in c++ and then assign the padded result to a variable?
I was looking at setfill
and setw
, but all examples I saw output the result with std::cout
. For instance:
std::cout << std::left << std::setfill('0') << std::setw(12) << 123;
I wanted something in the lines of:
auto padded {std::left << std::setfill('0') << std::setw(12) << 123};
Are there std functions to accomplish this or do I have to roll my own?
You could use ostringstream with the same format specifiers as for std::cout.
std::ostringstream ss;
ss << std::left << std::setfill('0') << std::setw(12) << 123;
And then
auto padded{ ss.str() };
Could use available string operations, like insert:
#include <iostream>
#include <string>
int main()
{
std::string s = "123";
s.insert(0, 12 - s.length(), '0');
std::cout << s << std::endl;
return 0;
}
https://ideone.com/ZhG00V
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