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
Create a new string of 10 spaces, and work backwards in both string.
string padstring(const string &source, size_t totalLength, char padChar)
{
if (source.length() >= totalLength)
return source;
string padded(totalLength, padChar);
string::const_reverse_iterator iSource = source.rbegin();
string::reverse_iterator iPadded = padded.rbegin();
for (;iSource != source.rend(); ++iSource, ++iPadded)
*iPadded = *iSource;
return padded;
}