Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ integer->std::string conversion. Simple function?

Problem: I have an integer; this integer needs to be converted to a stl::string type.

In the past, I've used stringstream to do a conversion, and that's just kind of cumbersome. I know the C way is to do a sprintf, but I'd much rather do a C++ method that is typesafe(er).

Is there a better way to do this?

Here is the stringstream approach I have used in the past:

std::string intToString(int i) {     std::stringstream ss;     std::string s;     ss << i;     s = ss.str();      return s; } 

Of course, this could be rewritten as so:

template<class T> std::string t_to_string(T i) {     std::stringstream ss;     std::string s;     ss << i;     s = ss.str();      return s; } 

However, I have the notion that this is a fairly 'heavy-weight' implementation.

Zan noted that the invocation is pretty nice, however:

std::string s = t_to_string(my_integer); 

At any rate, a nicer way would be... nice.

Related:

Alternative to itoa() for converting integer to string C++?

like image 490
Paul Nathan Avatar asked Nov 07 '08 22:11

Paul Nathan


People also ask

Which is the easiest way to convert an integer to a string in C?

sprintf() Function to Convert an Integer to a String in C This function gives an easy way to convert an integer to a string. It works the same as the printf() function, but it does not print a value directly on the console but returns a formatted string.

Which function converts string into integer in C?

int atoi (const char * str);


1 Answers

Now in c++11 we have

#include <string> string s = std::to_string(123); 

Link to reference: http://en.cppreference.com/w/cpp/string/basic_string/to_string

like image 104
Johannes Schaub - litb Avatar answered Sep 22 '22 02:09

Johannes Schaub - litb