Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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." 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).

like image 609
Ericson Willians Avatar asked Jun 22 '15 07:06

Ericson Willians


4 Answers

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';
}
like image 160
Galik Avatar answered Sep 24 '22 21:09

Galik


I'd like to answer it differently: just get mingw-w64.

Seriously, MinGW32 is just so full of issues it's not even funny:

  • http://sourceforge.net/p/mingw/bugs/1578/
  • http://sourceforge.net/p/mingw/mailman/message/23108552/
  • wWinmain, Unicode, and Mingw

With MinGW-w64 you get for free:

  • support for Windows Unicode entry point (wmain/wWinMain)
  • better C99 support
  • better C++11 support (as you see in your question!)
  • large file support
  • support for C++11 threads
  • support for Windows 64 bit
  • cross compiling! so you can work on your Windows app on your favorite platform.
like image 35
rr- Avatar answered Sep 23 '22 21:09

rr-


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;
}
like image 24
Ziming Song Avatar answered Sep 23 '22 21:09

Ziming Song


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);
}
like image 29
Jay Bosamiya Avatar answered Sep 25 '22 21:09

Jay Bosamiya