在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();
当前回答
使用字符串流进行数字转换是危险的!
请参阅std::ostream::operator<<,其中告诉operator<插入格式化输出。
根据您当前的语言环境,大于三位数的整数可以转换为四位数的字符串,并添加额外的千位分隔符。
例如,int=1000可以转换为字符串1.001。这可能会使比较操作根本不起作用。
所以我强烈建议使用std::to_string方法。它更容易,做你期望的事情。
从std::到_string:
C++17提供std::to_chars作为一种更高性能的独立于语言环境的替代方案。
其他回答
char * bufSecs = new char[32];
char * bufMs = new char[32];
sprintf(bufSecs, "%d", timeStart.elapsed()/1000);
sprintf(bufMs, "%d", timeStart.elapsed()%1000);
使用普通标准stdio标头,可以将sprintf上的整数强制转换为缓冲区,如下所示:
#include <stdio.h>
int main()
{
int x = 23;
char y[2]; // The output buffer
sprintf(y, "%d", x);
printf("%s", y)
}
记住根据您的需要(字符串输出大小)注意缓冲区的大小。
如果使用MFC,可以使用CString:
int a = 10;
CString strA;
strA.Format("%d", a);
我不知道,在纯C++中。但对你提到的内容稍作修改
string s = string(itoa(a));
应该有效,而且很短。
这对我有用-
我的代码:
#include <iostream>
using namespace std;
int main()
{
int n = 32;
string s = to_string(n);
cout << "string: " + s << endl;
return 0;
}