在C++中将int转换为等价字符串的最简单方法是什么?我知道两种方法。有没有更简单的方法?

(1)

int a = 10;
char *intStr = itoa(a);
string str = string(intStr);

(2)

int a = 10;
stringstream ss;
ss << a;
string str = ss.str();

当前回答

您只需在定义变量(StringintStr)时使用String。每当需要该变量时,调用whateverFunction(intStr.toInt())

其他回答

这对我有用-

我的代码:

#include <iostream>
using namespace std;

int main()
{
    int n = 32;
    string s = to_string(n);
    cout << "string: " + s  << endl;
    return 0;
}

使用字符串流会更容易:

#include <sstream>

int x = 42;          // The integer
string str;          // The string
ostringstream temp;  // 'temp' as in temporary
temp << x;
str = temp.str();    // str is 'temp' as string

或生成函数:

#include <sstream>

string IntToString(int a)
{
    ostringstream temp;
    temp << a;
    return temp.str();
}

我通常使用以下方法:

#include <sstream>

template <typename T>
  std::string NumberToString ( T Number )
  {
     std::ostringstream ss;
     ss << Number;
     return ss.str();
  }

这里将详细描述。

使用计数器类型的算法转换为字符串。我从编程Commodore 64计算机中获得了这种技术。它也适用于游戏编程。

你取整数,取每一个10次幂的数字。所以假设整数是950。如果整数等于或大于100000,则减去100000并将字符串中的计数器增加为[“000000”];继续这样做,直到没有更多的数字在位置100000。再降低10次方。如果整数等于或大于10000,则减去10000,并在[“000000”]+1位置增加字符串中的计数器;一直这样做,直到10000位不再有数字。再降低10次方重复该模式

我知道950太小了,不能作为一个例子,但我希望你能理解。

使用普通标准stdio标头,可以将sprintf上的整数强制转换为缓冲区,如下所示:

#include <stdio.h>

int main()
{
    int x = 23;
    char y[2]; // The output buffer
    sprintf(y, "%d", x);
    printf("%s", y)
}

记住根据您的需要(字符串输出大小)注意缓冲区的大小。