整型到字符串:不使用stoi库
Integer to String: Without using stoi library
我在书中发现了这个问题,它要求我们将Int转换为字符串。不使用stoi库例如,如果x=10,s="10"代码应该处理负数。
我在书中找到了这个解决方案。我在编译器中键入了它,但它只给出了第一个数字的字符串
因此,如果x=45,则给出"4"
我不理解这行s = '0' + x%10;
能够修复代码。他为什么要在字符串中添加"0"。什么是最好的解决方案。
这是代码:我在我理解的部分添加了注释
#include<iostream>
#include<string>
using namespace std;
void IntToString(int x);
int main()
{
int num;
cout << "Please enter a number" << endl;
cin >> num;
IntToString(num);
}
void IntToString(int x)
{
bool isNegative = false;
if(x < 0) //if its negative make boolean true
{
x = -x;
isNegative = true;
}
string s;
do
{
s = '0' + x%10; //modulus for getting the last number
x = x/10; //shorten the number
}while(x);
reverse(s.begin(), s.end()); //reverse the string since it starts from end
if(isNegative)
s = '-' + s;
cout << s << endl;
}
s = '0' + x%10;
将从x%10
中获取最后一位,并添加0
的ASCII,即48,给出所需最后一位的ASCII,使用其赋值运算符将副本分配给字符串s
。
顺便说一句,你需要:
s += '0' + x%10;
~~ // += operator
do ... while
循环的问题是,您只提取更改后的x
的最后一位,然后用倒数第二位替换它,以此类推,直到您得到存储在s
中的x
的第一位。
由于CCD_ 10实际上只包含一个字符,因此CCD_。
此外,我们将'0'
添加到s
,因为s
最初存储数字的整数值,添加'0'
将其转换为ASCII形式
示例:
void IntToString(int x)
{
bool isNegative = false;
if(x < 0)
{
x = -x;
isNegative = true;
}
string s;
do
{
//The below code appends the new number at the beginning of s.
s = ('0' + x%10) + s; //modulus for getting the last number
x = x/10; //shorten the number
}while(x);
if(isNegative)
main_string = '-' + main_string;
cout << main_string << endl;
}