如何在C++中将 int 转换为字符串
How to convert int to string in C++?
如何在C++中从int
转换为等效string
? 我知道有两种方法。还有别的办法吗?
(1(
int a = 10;
char *intStr = itoa(a);
string str = string(intStr);
(二(
int a = 10;
stringstream ss;
ss << a;
string str = ss.str();
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.conversions] (n3242 中的 21.5(
C++20: std::format 现在是惯用的方式。
<小时 />C++17:
几年后与 @v.oddou 进行了讨论,C++17 提供了一种方法来执行最初基于宏的类型不可知的解决方案(保留如下(,而无需经历宏观丑陋。
// variadic template
template < typename... Args >
std::string sstr( Args &&... args )
{
std::ostringstream sstr;
// fold expression
( sstr << std::dec << ... << args );
return sstr.str();
}
用法:
int i = 42;
std::string s = sstr( "i is: ", i );
puts( sstr( i ).c_str() );
Foo x( 42 );
throw std::runtime_error( sstr( "Foo is '", x, "', i is ", i ) );
<小时 />C++98:
由于"转换...字符串"是一个反复出现的问题,我总是在我的C++源的中心标头中定义 SSTR(( 宏:
#include <sstream>
#define SSTR( x ) static_cast< std::ostringstream & >(
( std::ostringstream() << std::dec << x ) ).str()
使用非常简单:
int i = 42;
std::string s = SSTR( "i is: " << i );
puts( SSTR( i ).c_str() );
Foo x( 42 );
throw std::runtime_error( SSTR( "Foo is '" << x << "', i is " << i ) );
以上是C++98兼容的(如果你不能使用C++11 std::to_string
(,并且不需要任何第三方包含(如果你不能使用Boost lexical_cast<>
(;虽然这两种其他解决方案都有更好的性能。
当前C++
从 C++11 开始,有一个用于整数类型的重载std::to_string
函数,因此您可以使用如下代码:
int a = 20;
std::string s = std::to_string(a);
// or: auto s = std::to_string(a);
该标准将这些定义为等效于使用 sprintf
(使用与提供的对象类型匹配的转换说明符,例如 %d
表示int
(进行转换到足够大小的缓冲区,然后创建该缓冲区内容的std::string
。
老C++
对于较旧的(C++11 之前(编译器,可能最常见的简单方法基本上是将您的第二选择包装到通常名为 lexical_cast
的模板中,例如 Boost 中的模板,因此您的代码如下所示:
int a = 10;
string s = lexical_cast<string>(a);
这样做的一个好处是它也支持其他强制转换(例如,在相反的方向上也可以工作(。
另请注意,尽管 Boost lexical_cast
最初只是写入stringstream
,然后从流中提取回来,但现在它有一些附加功能。首先,添加了相当多类型的专用化,因此对于许多常见类型,它比使用stringstream
要快得多。其次,它现在检查结果,因此(例如(如果您从字符串转换为int
,如果字符串包含无法转换为int
的内容(例如,1234
会成功,但123abc
会抛出(,它可能会引发异常(。
我通常使用以下方法:
#include <sstream>
template <typename T>
std::string NumberToString ( T Number )
{
std::ostringstream ss;
ss << Number;
return ss.str();
}
此处对此进行了详细描述。
你可以按照Matthieu M.的建议使用C++11中可用的std::to_string
:
std::string s = std::to_string(42);
或者,如果性能至关重要(例如,如果您进行了大量转换(,则可以使用 {fmt} 库中的fmt::format_int
将整数转换为 std::string
:
std::string s = fmt::format_int(42).str();
或 C 字符串:
fmt::format_int f(42);
const char* s = f.c_str();
后者不做任何动态内存分配,比libstdc++在Boost Karma基准测试上实现std::to_string
快70%以上。有关更多详细信息,请参阅将一亿个整数转换为每秒字符串。
免责声明:我是 {fmt} 库的作者。
如果你安装了 Boost(你应该(:
#include <boost/lexical_cast.hpp>
int num = 4;
std::string str = boost::lexical_cast<std::string>(num);
使用字符串流会更容易:
#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();
}
我不知道,在纯粹的C++。但是对你提到的内容稍作修改
string s = string(itoa(a));
应该可以工作,而且很短。
sprintf()
非常适合格式转换。然后,可以将生成的 C 字符串分配给C++字符串,就像在 1 中所做的那样。
使用字符串流进行数字转换是危险的!
请参阅 std::ostream::operator<<其中它告诉operator<<
插入格式化的输出。
根据您当前的区域设置,大于三位数字的整数可以转换为四位数字的字符串,并添加额外的千位分隔符。
例如,int = 1000
可以转换为字符串1.001
。这可能会使比较操作根本不起作用。
所以我强烈建议使用std::to_string
的方式。它更容易,并且可以满足您的期望。
从标准::to_string:
C++17 提供
std::to_chars
作为与区域设置无关的更高性能替代方案。
首先包括:
#include <string>
#include <sstream>
第二个添加方法:
template <typename T>
string NumberToString(T pNumber)
{
ostringstream oOStrStream;
oOStrStream << pNumber;
return oOStrStream.str();
}
使用如下方法:
NumberToString(69);
或
int x = 69;
string vStr = NumberToString(x) + " Hello word!."
在 C++11 中,我们可以使用 "to_string(("> 函数将 int 转换为字符串:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int x = 1612;
string s = to_string(x);
cout << s<< endl;
return 0;
}
C++17 提供std::to_chars
作为与区域设置无关的更高性能替代方案。
如果您需要将具有固定位数的整数快速转换为用"0"左填充的字符*,这是小端架构(所有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_t s = 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;
我认为它应该可以工作。
添加一些语法糖相当容易,允许人们以类似流的方式动态编写字符串
#include <string>
#include <sstream>
struct strmake {
std::stringstream s;
template <typename T> strmake& operator << (const T& x) {
s << x; return *this;
}
operator std::string() {return s.str();}
};
现在,您可以附加所需的任何内容(前提是为其定义了运算符<< (std::ostream& ..)
(来strmake()
并使用它来代替std::string
。
例:
#include <iostream>
int main() {
std::string x =
strmake() << "Current time is " << 5+5 << ":" << 5*5 << " GST";
std::cout << x << std::endl;
}
int i = 255;
std::string s = std::to_string(i);
在 C++ 中,to_string(( 将通过将整数值表示为字符序列来创建整数值的字符串对象。
使用:
#define convertToString(x) #x
int main()
{
convertToString(42); // Returns const char* equivalent of 42
}
我使用:
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++编译器。
C++11 引入了数值类型的std::to_string()
:
int n = 123; // Input, signed/unsigned short/int/long/long long/float/double
std::string str = std::to_string(n); // Output, std::string
这是另一种简单的方法:
char str[100];
sprintf(str, "%d", 101);
string s = str;
sprintf
众所周知,可以将任何数据插入所需格式的字符串中。
您可以将char *
数组转换为字符串,如第三行所示。
如果您使用的是Microsoft基础类库,则可以使用 CString
:
int a = 10;
CString strA;
strA.Format("%d", a);
使用:
#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;
}
要做的就是在定义变量时使用String
(String intStr
(。每当需要该变量时,调用whateverFunction(intStr.toInt())
<</p>
使用普通的标准 stdio 标头,您可以将 sprintf 上的整数转换为缓冲区,如下所示:
#include <stdio.h>
int main()
{
int x = 23;
char y[2]; // The output buffer
sprintf(y, "%d", x);
printf("%s", y)
}
请记住根据需要处理缓冲区大小(字符串输出大小(。
使用我的函数"inToString">
它接受一个名为"number"的整数参数
请记住,您可以将参数类型更改为 FLOAT 或 DOUBLE,而不是 INT,如下所示:
"inToString(float number("或"inToString(double number(">
它可以正常工作,但请确保给它相同的类型 ^_^
#include<iostream>
#include<sstream>
using namespace std;
string inToString(int number){
stringstream stream;
stream << number;
string outString;
stream >> outString;
return outString;
}
int main(){
int number = 100;
string stringOut = inToString(number);
cout << "stringOut : " + stringOut << endl;
return 0;
}
string number_to_string(int x) {
if (!x)
return "0";
string s, s2;
while(x) {
s.push_back(x%10 + '0');
x /= 10;
}
reverse(s.begin(), s.end());
return s;
}
这对我有用 -
我的代码:
#include <iostream>
using namespace std;
int main()
{
int n = 32;
string s = to_string(n);
cout << "string: " + s << endl;
return 0;
}
<</div>
div class="answers">我认为使用stringstream
非常简单:
string toString(int n)
{
stringstream ss(n);
ss << n;
return ss.str();
}
int main()
{
int n;
cin >> n;
cout << toString(n) << endl;
return 0;
}
char * bufSecs = new char[32];
char * bufMs = new char[32];
sprintf(bufSecs, "%d", timeStart.elapsed()/1000);
sprintf(bufMs, "%d", timeStart.elapsed()%1000);
namespace std
{
inline string to_string(int _Val)
{ // Convert long long to string
char _Buf[2 * _MAX_INT_DIG];
snprintf(_Buf, "%d", _Val);
return (string(_Buf));
}
}
您现在可以使用 to_string(5)
.
- wcstombs_s(),转换字符串的长度
- 使用 CStringW/CStringA 和 CT2W/CT2A 转换字符串有什么区别?
- 无法转换字符串插入函数的参数
- 转换字符串向量:基于先前的值跳过元素
- 从中间器转换字符串不起作用,出了什么问题?
- 失败的证明转换字符串到枚举类
- 如何使用正则表达式和提升转换迭代器标记和转换 c 字符串
- 使用java jni时转换字符串类型
- 如何避免在转换字符串令牌流时重复istringstream构造
- 阿托伊未正确转换字符串
- C++,转换字符串,使连续下划线序列变为单个下划线
- 使用长算术转换字符串
- 转换字符串十进制数时的精度
- 将词法转换字符串提升为双精度
- 使用marshal_as函数转换字符串的性能
- C++不会从数据转换字符串
- 无论如何,在c++ /Qt中转换字符串到结构中的字段
- C++ 隐式类型转换字符串 -> int?
- 转换字符串到浮点数,c++实现
- 用于转换字符串大小写的函数