[英]How can I convert an int to a string in C++11 without using to_string or stoi?
我知道这听起来很愚蠢,但我在Windows7上使用MinGW32,并且“在此范围内未声明to_string
。” 这是一个真正的GCC Bug ,我已经按照这些说明进行操作了 。 那么,如何在不使用to_string
或stoi
情况下将int转换为C ++ 11中的字符串? (另外,我启用了-std=c++11
标志)。
它不是最快的方法,但你可以这样做:
#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';
}
我想以不同的方式回答:只需要mingw-w64。
说真的,MinGW32充满了问题,甚至都不好笑:
使用MinGW-w64,您可以免费获得:
wmain
/ wWinMain
) 你可以使用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;
}
您可以使用自己的功能来完成它。
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);
}
尽管之前的答案更好,但我希望在下一个旧的学校代码之后为您提供另一种实现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.