Reputation: 120
As I have been looking on this topic for a lot of time on this site, I couldn't find a helpful solution to my problem. So here's my problem :
If I have any number, say num = 256, I want to save this number in a character array, say a[10], like :
a[0] = 2
a[1] = 5
a[2] = 6
Storing in their respective indices
also the num variable is not static and it's value is dynamically entered by the user on runtime. But the size of the character array will be static.
Upvotes: 0
Views: 374
Reputation: 48258
a way is decomposing the number in hundred, tens and units... modulo can help and log10 will be useful too:
this is going to be a nice work around if you arent allowed to convert to string
here an example:
int value = 256;
int myArray[3];
auto m = static_cast<int>(ceil(log10(value)));
for(int i =0; i < m; ++i)
{
myArray[m-1-i] = static_cast<int>(value/pow(10,i))%10;
}
Upvotes: 1
Reputation: 34628
You can convert an integral value to its decimal representation with std::to_string
:
std::string const dec = std::to_string(num);
If you have a character array, say char a[4]
, you can copy the data there element-wise:
for (std::size_t i = 0; std::begin(a) + i < std::end(a) && i < dec.size(); ++i) {
a[i] = dec[i] - '0';
}
Edit: See Konrad Rudolph's answer for a simpler (and presumably faster) way of doing this.
Upvotes: 2
Reputation: 545588
C++17 has std::to_chars
for this purpose:
char a[10];
if (auto const result = std::to_chars(a, a + sizeof a - 1, 256); result.ec != std::errc()) {
// An error occurred.
} else {
*result.ptr = '\0';
}
Upvotes: 2