Guus Geurkink
Guus Geurkink

Reputation: 713

Add leading zeroes to string, without (s)printf

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.

Does anybody of the readers know a way?

Upvotes: 56

Views: 140691

Answers (7)

Ruslan Guseinov
Ruslan Guseinov

Reputation: 1331

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".

Upvotes: 133

Genhis
Genhis

Reputation: 1524

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

Upvotes: 7

Ivan Strelets
Ivan Strelets

Reputation: 242

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

Upvotes: 8

Robᵩ
Robᵩ

Reputation: 168616

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

Upvotes: 68

Jerry Coffin
Jerry Coffin

Reputation: 490098

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.

Upvotes: 33

Michael Burr
Michael Burr

Reputation: 340188

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

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

Upvotes: 14

Seth Robertson
Seth Robertson

Reputation: 31441

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.

Upvotes: 1

Related Questions