Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ convert simple values to string

Tags:

Right now I use the following piece of code to dummily convert basic types (int, long, char[], this kind of stuff) to std::string for further processing:

template<class T> constexpr std::string stringify(const T& t) {     std::stringstream ss;     ss << t;     return ss.str(); } 

however I don't like the fact that it depends on std::stringstream. I tried using std::to_string (from C++11's repertoire) however it chokes on char[] variables.

Is there a simple way offering an elegant solution for this problem?

like image 997
Ferenc Deak Avatar asked May 11 '15 11:05

Ferenc Deak


People also ask

How do I convert a number to a string in C?

itoa() Function to Convert an Integer to a String in C itoa() is a type casting function in C. This function converts an integer to a null-terminated string. It can also convert a negative number.

What is Strtol () in C?

The strtol library function in C converts a string to a long integer. The function works by ignoring any whitespace at the beginning of the string, converting the next characters into a long integer, and stopping when it comes across the first non-integer character.

Is there an itoa function in C?

Implement itoa() function in C The standard itoa() function converts input number to its corresponding C-string using the specified base. Prototype: The prototype of the itoa() is: char* itoa(int value, char* buffer, int base);


1 Answers

As far as I know the only way of doing this is by specialising the template by the parameter type with SFINAE.

You need to include the type_traits.

So instead of your code use something like this:

template<class T>  typename std::enable_if<std::is_fundamental<T>::value, std::string>::type stringify(const T& t)   {     return std::to_string(t);   }  template<class T>   typename std::enable_if<!std::is_fundamental<T>::value, std::string>::type  stringify(const T& t)   {     return std::string(t);   } 

this test works for me:

int main() {   std::cout << stringify(3.0f);   std::cout << stringify("Asdf"); } 

Important note: the char arrays passed to this function need to be null terminated!

As noted in the comments by yakk you can get rid of the null termination with:

template<size_t N> std::string stringify( char(const& s)[N] ) {      if (N && !s[N-1]) return {s, s+N-1};     else return {s, s+N};  } 
like image 188
cerkiewny Avatar answered Oct 01 '22 03:10

cerkiewny