Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Padding and assigning a std::string in c++

Tags:

c++

padding

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?

like image 209
Marco Luglio Avatar asked Dec 14 '22 19:12

Marco Luglio


2 Answers

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() };
like image 79
tomix86 Avatar answered Jan 12 '23 00:01

tomix86


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

like image 31
Killzone Kid Avatar answered Jan 12 '23 01:01

Killzone Kid