[英]How can I convert an int to a string in C++11 without using to_string or stoi?
I know it sounds stupid, but I'm using MinGW32 on Windows7, and " to_string
was not declared in this scope." 我知道这听起来很愚蠢,但我在Windows7上使用MinGW32,并且“在此范围内未声明
to_string
。” It's an actual GCC Bug , and I've followed these instructions and they did not work. 这是一个真正的GCC Bug ,我已经按照这些说明进行操作了 。 So, how can I convert an int to a string in C++11 without using
to_string
or stoi
? 那么,如何在不使用
to_string
或stoi
情况下将int转换为C ++ 11中的字符串? (Also, I have the -std=c++11
flag enabled). (另外,我启用了
-std=c++11
标志)。
Its not the fastest method but you can do this: 它不是最快的方法,但你可以这样做:
#include <string>
#include <sstream>
#include <iostream>
template<typename ValueType>
std::string stringulate(ValueType v)
{
std::ostringstream oss;
oss << v;
return oss.str();
}
int main()
{
std::cout << ("string value: " + stringulate(5.98)) << '\n';
}
I'd like to answer it differently: just get mingw-w64. 我想以不同的方式回答:只需要mingw-w64。
Seriously, MinGW32 is just so full of issues it's not even funny: 说真的,MinGW32充满了问题,甚至都不好笑:
With MinGW-w64 you get for free: 使用MinGW-w64,您可以免费获得:
wmain
/ wWinMain
) wmain
/ wWinMain
) You can use stringstream
. 你可以使用
stringstream
。
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main() {
int num = 12345;
stringstream ss;
ss << num;
string str;
ss >> str;
cout << str << endl;
return 0;
}
You could roll your own function to do it. 您可以使用自己的功能来完成它。
std::string convert_int_to_string (int x) {
if ( x < 0 )
return std::string("-") + convert_int_to_string(-x);
if ( x < 10 )
return std::string(1, x + '0');
return convert_int_to_string(x/10) + convert_int_to_string(x%10);
}
Despite the fact that previous answers are better I want to give you another possibility to implement an INT to STRING method following the next old school code: 尽管之前的答案更好,但我希望在下一个旧的学校代码之后为您提供另一种实现INT到STRING方法的可能性:
#include <string>
std::string int2string(int value) {
char buffer[20]; // Max num of digits for 64 bit number
sprintf(buffer,"%d", value);
return std::string(buffer);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.