使用 push_back 将整数放入字符串

Put integer in to string using push_back

我正在尝试使用以下代码将整数放入字符串中:

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

但是当我尝试输出字符串时,它出现了有线字符。你能帮忙看看这段代码中发生了什么吗??

已编辑: ps。我想以实物手动方式做到这一点。表示我不想使用 to_string

std::to_stringstring::append一起使用:

while (x > 0)
{
    num.append(std::to_string(x % 10));
    x = x / 10;
}

使用 push_back 迫使你做更多的工作。

会有 奇怪的 字符,因为当您 push_back() 时,整数会 转换(或更确切地说,解释)为相应的 ASCII 字符,然后推回字符串。

前进的方法是通过向整数值添加 '0' 将整数转换为字符。

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

整数加'0'的原因?

0的ASCII值是48,1是49,2是50等等...所以,我们这里基本上做的就是把48(0的ASCII值)加到对应的整数上,使它等于它的 ASCII 等价物。顺便说一下,'0' 等于 48 因为它 0 字符 .

的 ASCII 值]

要转换您可以使用的整数:

  1. 字符操作:shifting/adding '0'表示ASCII,从而使int值变成char值。
  2. 类型转换 new_type(old_type),还有一些额外的 types of casting

要扩展字符串的长度,您可以使用:

  1. 字符串 member functions 如:push_back(value)append(append).
  2. Concatenation operator 赞:str += value

一个可能的实现是:

while(x > 0)
{
 num+=((x % 10) + '0');                             
 x = x / 10;
}