Home > Net >  How to convert integer to string, preserving leading zeroes in C ? (Using to_string)
How to convert integer to string, preserving leading zeroes in C ? (Using to_string)

Time:11-03

When I am trying to convert the given integer to string through to_string function, It simply omits the leading zeroes of the integer.

Why ? & how to overcome this?

#include<iostream>

using namespace std;

int main(){
int n;
cin >> n;

string s = to_string(n);

cout << s;
}

CodePudding user response:

Integers doesn't have leading zeroes.

If you want a specific number of digits for the number, with leading zeros, you need to use I/O manipulators like set::setw and std::setfill:

std::cout << std::setw(8) << std::setfill('0') << n << '\n';

That will print (at least) eight digits, with leading zeros if the value of n is not eight digits.


If you want to store a "number" with leading zeros in your program, for example a phone number or similar, then you need another data-type than plain integers (which as mentioned doesn't have leading zeros).

Most common is as a string (std::string).

CodePudding user response:

In C 20, you can use std::format when it is supported by your compiler. So as for now, there isn't a convenient way to transform a number in a string with formatted output.

This answer already showed the solution with iostreams which I normally prefer, but for formatting, I think it's too verbose and some manipulators are remembered by the iostream while others aren't, so in this case, I advise to use the C-style std::snprintf (maybe a bit controversial in C ). The formatting also needs some learning but is more concise. The string is written in a char array that the caller has to provide and the result has then to be copied to a string.

int inp = 28;
char result[10];
int len = std::snprintf(result, 9, "d", inp);
std::string str_res(result, len);
  • Related