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 th开发者_开发问答is without (s)printf
.
Does anybody of the readers know a way?
I can give this one-line solution if you want a field of n_zero
zeros:
auto new_str = std::string(n_zero - std::min(n_zero, old_str.length()), '0') + old_str;
For example, for std::string old_str = "45"; size_t n_zero = 4;
you get new_str == "0045"
.
You could use std::string::insert
, std::stringstream
with stream manipulators, or Boost.Format :
#include <string>
#include <iostream>
#include <iomanip>
#include <boost/format.hpp>
#include <sstream>
int main() {
std::string s("12");
s.insert(0, 3, '0');
std::cout << s << "\n";
std::ostringstream ss;
ss << std::setw(5) << std::setfill('0') << 12 << "\n";
std::string s2(ss.str());
std::cout << s2;
boost::format fmt("%05d\n");
fmt % 12;
std::string s3 = fmt.str();
std::cout << s3;
}
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.
// assuming that `original_string` is of type `std:string`:
std::string dest = std::string( number_of_zeros, '0').append( original_string);
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();
}
If you want to modify the original string instead of creating a copy, you can use std::string::insert()
.
std::string s = "123";
unsigned int number_of_zeros = 5 - s.length(); // add 2 zeros
s.insert(0, number_of_zeros, '0');
Result:
00123
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.
精彩评论