在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();
在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();
当前回答
Use:
#include<iostream>
#include<string>
std::string intToString(int num);
int main()
{
int integer = 4782151;
std::string integerAsStr = intToString(integer);
std::cout << "integer = " << integer << std::endl;
std::cout << "integerAsStr = " << integerAsStr << std::endl;
return 0;
}
std::string intToString(int num)
{
std::string numAsStr;
bool isNegative = num < 0;
if(isNegative) num*=-1;
do
{
char toInsert = (num % 10) + 48;
numAsStr.insert(0, 1, toInsert);
num /= 10;
}while (num);
return isNegative? numAsStr.insert(0, 1, '-') : numAsStr;
}
其他回答
char * bufSecs = new char[32];
char * bufMs = new char[32];
sprintf(bufSecs, "%d", timeStart.elapsed()/1000);
sprintf(bufMs, "%d", timeStart.elapsed()%1000);
我通常使用以下方法:
#include <sstream>
template <typename T>
std::string NumberToString ( T Number )
{
std::ostringstream ss;
ss << Number;
return ss.str();
}
这里将详细描述。
如果您需要将具有固定位数的整数快速转换为左填充“0”的char*,这是little-endian体系结构(所有x86、x86_64和其他)的示例:
如果要转换两位数:
int32_t s = 0x3030 | (n/10) | (n%10) << 8;
如果要转换三位数:
int32_t s = 0x303030 | (n/100) | (n/10%10) << 8 | (n%10) << 16;
如果要转换四位数:
int64_t s = 0x30303030 | (n/1000) | (n/100%10)<<8 | (n/10%10)<<16 | (n%10)<<24;
如此类推,直到七位数。在本例中,n是给定的整数。转换后,它的字符串表示形式可以访问为(char*)&s:
std::cout << (char*)&s << std::endl;
注意:如果您需要使用大端字节顺序,虽然我没有测试它,但这里有一个示例:对于三位数,它是int32_ts=0x00303030|(n/100)<<24|(n/10%10)<<16|(n/10)<<8;对于四位数(64位拱门):int64_t s=0x0000000030303030 |(n/1000)<<56 |(n/100%10)<<48 |(n/10%10)<<40 |(n/10%)<<32;我认为它应该起作用。
C++11引入了std::stoi(以及每种数字类型的变体)和std::to_string,这是C atoi和itoa的对应项,但用std::string表示。
#include <string>
std::string s = std::to_string(42);
因此,这是我能想到的最短的方法。您甚至可以使用auto关键字省略对类型的命名:
auto s = std::to_string(42);
注:请参见[string.converts](n3242中的21.5)
我使用:
int myint = 0;
long double myLD = 0.0;
string myint_str = static_cast<ostringstream*>(&(ostringstream() << myint))->str();
string myLD_str = static_cast<ostringstream*>(&(ostringstream() << myLD))->str();
它适用于我的Windows和Linux g++编译器。