Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Padding stl strings in C++

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)

like image 732
Alex B Avatar asked Mar 20 '09 17:03

Alex B


People also ask

What is string padding in C?

@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.

What is padding in string?

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.

How do you fill a string in C++?

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.


1 Answers

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>

like image 58
bayda Avatar answered Sep 20 '22 03:09

bayda