Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put integer in to string using push_back

I am trying to put an integer in to string using the following code:

int x = 42;
string num;
bool negative = false;

if(x < 0)
{
   negative = true;
   x = x * -1;
}
while(x > 0)
{
  num.push_back(x % 10);
  x = x / 10;
}

But when I try to output the string, it comes up with the wired character. Could you please help what's happening in this code??

Edited: ps. I want to do this in kind manual way. Means I don't want to use to_string

like image 388
Krin Yongvongphaiboon Avatar asked Dec 30 '25 13:12

Krin Yongvongphaiboon


1 Answers

There would be weird characters, because when you push_back(), the integer is converted (or rather interpreted) into its corresponding ASCII character, and then pushed back into the string.

The way forward is to convert the integer to a character by adding a '0' to the integer value.

while(x > 0)
{
  num.push_back((x % 10) + '0'); //Adding '0' converts the number into
                                 //its corresponding ASCII value.
  x = x / 10;
}

The reason to add a '0' to the integer?

The ASCII value of 0 is 48, 1 is 49, 2 is 50 and so on... Hence, what we basically do here is to add 48 (The ASCII value of 0) to the corresponding integer to make it equal to its ASCII equivalent. Incidentally, '0' is equal to 48 because it is the ASCII value of the 0 character.

like image 54
shauryachats Avatar answered Jan 01 '26 02:01

shauryachats



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!