Padding Stl Strings in C++

Padding stl strings in C++

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>

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

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() };

Add leading zeroes to string, without (s)printf

// assuming that `original_string` is of type `std:string`:

std::string dest = std::string( number_of_zeros, '0').append( original_string);

Why is 'insert' faster than 'append' in string padding?

Insert is fastest because you tell it to add 20 MB of zeros all at once, and it can allocate a single time. Append is a bit slower because it has to allocate 20 MB of zeros then copy them. The loop is slow because it has to constantly reallocate more and more, which you could at least partially fix if you called paddingstr.reserve(20000*1024 + paddingstr.size()) first. And the ostringstream is slow because stringstreams are usually slow, plus you copy to the string at the end.

Padding specified number of zeros to a char array

If you're fine with std::string (and I think you should be), you can make use of its fill constructor:

char        s[]    = "12";
std::string padded = std::string( (15 - strlen(s) ), '0').append(s);

Of course you might want to check whether strlen(s) > 15 first.

Converting number to a padded string

Your problem happens because you are passing a reference to arithmeticToMaxLengthString function. For reasons listed in another answer here, std::numeric_limits does not work with references.

Therefore, I am suggesting you to use template type T for getting the numerical limit instead of using decltype(value):

result = lpad('0', std::numeric_limits<T>::digits10 + 1, number);

Not only does it solve the problem, it looks much more elegant too.

C++ can setw and setfill pad the end of a string?

You can use manipulators std::left, std::right, and std::internal to choose where the fill characters go.

For your specific case, something like this could do:

#include <iostream>
#include <iomanip>
#include <string>

const char* C_TEXT = "Constant text ";
const size_t MAXWIDTH = 10;

void print(const std::string& var_text, int num)
{
std::cout << C_TEXT
// align output to left, fill goes to right
<< std::left << std::setw(MAXWIDTH) << std::setfill('.')
<< var_text << ": " << num << '\n';
}

int main()
{
print("1234567890", 42);
print("12345", 101);
}

Output:

Constant text 1234567890: 42
Constant text 12345.....: 101

EDIT:
As mentioned in the link, std::internal works only with integer, floating point and monetary output. For example with negative integers, it'll insert fill characters between negative sign and left-most digit.

This:

int32_t i = -1;
std::cout << std::internal
<< std::setfill('0')
<< std::setw(11) // max 10 digits + negative sign
<< i << '\n';
i = -123;
std::cout << std::internal
<< std::setfill('0')
<< std::setw(11)
<< i;

will output

-0000000001
-0000000123

how to zero pre-fill for std::to_string function?

Instead of using std::to_string(), you could use a std::ostringstream. The IO manipulators will work with a std::ostringstream.

#include <iostream>
#include <sstream>
#include <iomanip>

int main()
{
for ( int i = 1; i <= 10; ++i )
{
std::ostringstream str;
str << std::setw(3) << std::setfill('0') << i;
std::cout << str.str() << std::endl;
}
}

Output:

001
002
003
004
005
006
007
008
009
010

See it working at https://ideone.com/ay0Xzp.

Packing a struct that contains a string

A good rule of thumb is to sort your members from biggest to smallest. That way your data is aligned and (usually) has no gaps. E.g. on VS2013 for an x64 target the following layout requires 112 instead of 128 bytes:

struct B {  
string s,t,u;
int a,b,c;
char x,y;
};

For an x86 target however, this only saves you 4 bytes. Whether or not and how this impacts your performance depends on so many other factors, that it can only be determined by measurement.



Related Topics



Leave a reply



Submit