我在书中找到了这个问题,它要求我们将一个 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
关于c++ - 整数到字符串 : Without using stoi library,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29158855/