Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a number to a string with specified length in C++

I have some numbers of different length (like 1, 999, 76492, so on) and I want to convert them all to strings with a common length (for example, if the length is 6, then those strings will be: '000001', '000999', '076492').

In other words, I need to add correct amount of leading zeros to the number.

int n = 999; string str = some_function(n,6); //str = '000999' 

Is there a function like this in C++?

like image 912
Degvik Avatar asked Oct 22 '08 11:10

Degvik


People also ask

How do you convert a number variable value to a string?

Using the str() Function The str() function can be used to change any numeric type to a string. The nice thing about str() is that it can handle converting any type of number to a string, so you don't need to worry about choosing the correct method based on what type of number you're converting.

Is the easiest way to convert an integer to a string in C?

The logic is very simple. Here we will use the sprintf() function. This function is used to print some value or line into a string, but not in the console. This is the only difference between printf() and sprintf().


1 Answers

or using the stringstreams:

#include <sstream> #include <iomanip>  std::stringstream ss; ss << std::setw(10) << std::setfill('0') << i; std::string s = ss.str(); 

I compiled the information I found on arachnoid.com because I like the type-safe way of iostreams more. Besides, you can equally use this code on any other output stream.

like image 117
xtofl Avatar answered Sep 21 '22 16:09

xtofl