c++ - 手动将整数变量放入字符串中

标签 c++ string integer

我有一个关于以下代码的快速问题

int main()
{
    string data;
    int x;
    cin >> x;

    if (x < 0)
    {
        data = to_string(x);
    }
    else
    {
        data = to_string(x);
    }
   return 0;
}

如果我不想使用to_string(x),而是想手动做一些事情。无论如何我可以做到吗?如果我使用 data = x; 这显然行不通。

附言。我也不想使用 atoi

最佳答案

您可以执行以下操作:

int main(){
    int x;
    cin>>x;
    string s = "";     // s will represent x but with the digits reversed
    bool neg = 0;      // this flag is 1 if x is negative and 0 if positive. 
                       // we will use it to find out if we should put a "-" before the number
    if(x < 0){
        neg = 1;
        x *= -1;       // making the number positive
    }
    while(x){
        char c = '0' + x % 10;          // c represent the least significant digit of x
        s.push_back(c);                 // adding c to s             
        x /= 10;                        // removing the least significant digit of x
    }
    string ans = "";                    // ans is our resulting string
    if(neg) ans.push_back('-');         // adding a negative sign if x was negative
    for(int i=s.size() - 1; i >= 0; i--)    // adding the characters of s in reverse order
        ans.push_back(s[i]);
}

关于c++ - 手动将整数变量放入字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29424726/

相关文章:

c++ - LNK2019 构建 ZeroMQ Hello World 示例时出错。 VS2012 遥控

Javascript 底层 toString 转换

android - Strings.xml 不识别汉字

c++ - 是否有检索整数输入的函数?

java - 在不使用数组的情况下获取整数的最低和最高值?

c++ - QResource:注销 .rcc 文件

c++ - 这是实现自定义事件处理程序的正确方法吗?

php - 如何在 PHP 中的数字之间插入连字符?

javascript - 如何在纯 JavaScript(不是 Node.js)中生成一个范围内的随机 BigInt?

c# - C++ 是否支持单个泛型方法而不是泛型类?