I'm using std::string
and need to left pad them to a given width. What is the recommended way to do this in C++?
Sample input:
123
pad to 10 characters.
Sample output:
123
(7 spaces in front of 123)
@litb, strncpy: If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.
String padding refers to adding, usually, non-informative characters to a string to one or both ends of it. This is most often done for output formatting and alignment purposes, but it can have useful practical applications.
To fill in a string with content of a given size, you can use the corresonding constructor: std::string str( width, ' ' ); To fill in strings you can use the replace method: str.
std::setw (setwidth) manipulator
std::cout << std::setw (10) << 77 << std::endl;
or
std::cout << std::setw (10) << "hi!" << std::endl;
outputs padded 77 and "hi!".
if you need result as string use instance of std::stringstream instead std::cout object.
ps: responsible header file <iomanip>
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