c++ - 整数到字符串 : Without using stoi library

标签 c++

我在书中找到了这个问题,它要求我们将一个 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/

相关文章:

c++ - QObject::connect timer with update() 函数

c# - 如何检测应用程序是否受内存限制?

c++ - CreateProcess STATUS_DLL_NOT_FOUND - 哪个 dll?

c++ - 附加到具有非动态分配堆栈的 vector

C++ 创建和使用类

即使在使用 break 时,C++ switch 也会陷入默认状态;

c++ - 构建 boost 错误 : Name clash for '<pstage\lib>boost_system-vc120-mt-1_58.dll'

c++ - 分解/重构程序

c++ - 捕获到缓冲区 QT

c++ - 像 vector 一样访问 vector 中结构元素的函数