Reputation: 7845
I know it sounds stupid, but I'm using MinGW32 on Windows7, and "to_string
was not declared in this scope." It's an actual GCC Bug, and I've followed these instructions and they did not work. So, how can I convert an int to a string in C++11 without using to_string
or stoi
? (Also, I have the -std=c++11
flag enabled).
Upvotes: 6
Views: 9739
Reputation: 1879
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:
#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);
}
Upvotes: 1
Reputation: 14811
I'd like to answer it differently: just get mingw-w64.
Seriously, MinGW32 is just so full of issues it's not even funny:
With MinGW-w64 you get for free:
wmain
/wWinMain
)Upvotes: 4
Reputation: 1346
You can use 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;
}
Upvotes: 2
Reputation: 3209
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);
}
Upvotes: 1
Reputation: 48625
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';
}
Upvotes: 9