如何将 int 转换为字符串?

How to turn an int into a string?

我一直在尝试寻找如何在线进行操作。我被限制不能使用现成的函数,比如 to_stringboost::lexical_cast,甚至 <sstream> 库。我该如何应对这些限制?

您可以使用'0' + i获取0的char值并对其进行偏移。即

#include <cmath>
#include <string>
#include <iostream>

int main() {
    int number = 12345678;

    int nrDigits = std::log10(number)+1;

    std::string output(nrDigits, '0'); // just some initialization

    for (int i = nrDigits - 1; i >= 0; i--) {
        output[i] += number % 10;
        number /= 10;
    }

    std::cout << "number is " << output << '\n';
}

这是一种方法:

std::string int_to_string (int i)
{
    bool negative = i < 0;
    if (negative)
        i = -i;
    std::string s1;

    do
    {
        s1.push_back (i % 10 + '0');
        i /= 10;
    }
    while (i);
    
    std::string s2;
    if (negative)
        s2.push_back ('-');
    for (auto it = s1.rbegin (); it != s1.rend (); ++it)
        s2.push_back (*it);
    return s2;
}

我避免使用 std::reverse,假设它会是 off-limits。

Live demo