Kri*_*oon 2 c++ string integer
我试图使用以下代码将一个整数放入字符串:
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;
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试输出字符串时,它会出现有线字符.你能帮忙帮忙解决这段代码中发生的事情吗?
编辑:ps.我想以亲切的手动方式做到这一点.意味着我不想使用to_string
会有奇怪的字符,因为当你push_back(),整数被转换(或者说解释)成相应的ASCII字符,然后被推回到字符串中.
前进的方法是通过向'0'整数值添加a将整数转换为字符.
while(x > 0)
{
num.push_back((x % 10) + '0'); //Adding '0' converts the number into
//its corresponding ASCII value.
x = x / 10;
}
Run Code Online (Sandbox Code Playgroud)
'0'到整数的原因是什么?ASCII值为0是48,1是49,2是50等等...因此,我们在这里基本上做的是将48(ASCII值为0)添加到相应的整数,使其等于其ASCII当量.顺便提及,'0'是等于48,因为它是在的ASCII值0 字符.
| 归档时间: |
|
| 查看次数: |
1926 次 |
| 最近记录: |