views:

1932

answers:

8

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, prior to 123)

A: 

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;
}
Eclipse
+9  A: 

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>

bb
It's worth pointing out that this is a manipulation of the output method (std::ostream), and not a std::string. This is still probably one of the better ways to achieve your goal. Reference: http://www.cplusplus.com/reference/iostream/manipulators/setw.html
luke
yeah now with the example it's much clearer
Johannes Schaub - litb
+1  A: 
void padTo(std::string &str, const size_t num, const char paddingChar = ' ')
{
    if(num > str.size())
     str.insert(0, num - str.size(), paddingChar);
}

int main(int argc, char **argv)
{
    std::string str = "abcd";
    padTo(str, 10);
    return 0;
}
Brian R. Bondy
This will just add 10 spaces. Your example should only add 6.
greyfade
ok I see, fixed.
Brian R. Bondy
A: 

Hi,

you can create a string containing N spaces by calling

string(N, ' ');

So you could do like this:

string to_be_padded = ...;
if (to_be_padded.size() < 10) {
  string padded(10 - to_be_padded.size(), ' ');
  padded += to_be_padded;
  return padded;
} else { return to_be_padded; }
antti.huima
A: 

There's a nice and simple way :)

const int required_pad = 10;

std::string myString = "123";
size_t length = myString.length();

if (length < required_pad)
  myString.insert(0, required_pad - length, ' ');
Andrew Grant
wrong. need to be 10 - length of 123
Mykola Golubyev
Yes, I misread the requirement. fixed.
Andrew Grant
Still to rude. and too much code.
Mykola Golubyev
A: 

How about:

string s = "          "; // 10 spaces
string n = "123";
n.length() <= 10 ? s.replace(10 - n.length(), n.length(), s) : s = n;
Andy Mikula
A: 

You can use it like this:

std::string s = "123";
s.insert(s.begin(), paddedLength - s.size(), ' ');
Naveen
+4  A: 

The easiest way I can think of would be with a stringstream:

string foo = "foo";
stringstream ss;
ss << setw(10) << foo;
foo = ss.str();

foo should now be padded.

greyfade