I want to add a variable of leading zero\'s to a string. I couldn\'t find anything on Google, without someone mentioning (s)printf, but I want to do this without (s)printf.<
You could do something like:
std::cout << std::setw(5) << std::setfill('0') << 1;
This should print 00001
.
Note, however, that the fill-character is "sticky", so when you're done using zero-filling, you'll have to use std::cout << std::setfill(' ');
to get the usual behavior again.
memcpy(target,'0',sizeof(target));
target[sizeof(target)-1] = 0;
Then stick whatever string you want zero prefixed at the end of the buffer.
If it is an integer number, remember log_base10(number)+1
(aka ln(number)/ln(10)+1
) gives you the length of the number.
// assuming that `original_string` is of type `std:string`:
std::string dest = std::string( number_of_zeros, '0').append( original_string);
The C++ way of doing it is with setw, ios_base::width and setfill
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int a = 12;
const int b = 6;
cout << setw(width) << row * col;
cout << endl;
return 0;
}
I can give this one-line solution if you want a field of n_zero zeros:
std::string new_string = std::string(n_zero - old_string.length(), '0') + old_string;
For example: old_string = "45"; n_zero = 4; new_string = "0045";
This works well for me. You don't need to switch setfill back to ' ', as this a temporary stream.
std::string to_zero_lead(const int value, const unsigned precision)
{
std::ostringstream oss;
oss << std::setw(precision) << std::setfill('0') << value;
return oss.str();
}