Tag Archives: tostring
C++ || Snippet – Custom Template “ToString” Function For Primitive Data Types
The following is a custom template “ToString” function which converts the value of a primitive data type (i.e: int, double, long, unsigned, char, etc.) to an std::string. So for example, if you wanted to convert an integer value to an std::string, the following function can do that for you.
This function works by accepting a primitive datatype as a function parameter, then using the std::stringstream class to convert and return an std::string object containing the representation of that incoming function parameter as a sequence of characters.
The code demonstrated on this page is different from the std::to_string function in that this implementation does not require a compiler to have >= C++11 support. This function should work on any compiler.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
// ============================================================================ // Author: K Perkins // Date: Oct 27, 2013 // Taken From: http://programmingnotes.org/ // File: ToString.cpp // Description: Demonstrates the use of a custom "ToString" function // which converts a value of a primitive data type (int, double, long, // unsigned, char, etc.) to an std::string. // ============================================================================ #include <iostream> #include <string> #include <sstream> using namespace std; // function prototype template<typename ItemType> string ToString(const ItemType& value); int main() { // declare variables int inum = -1987; double fnum = 7.28; long lnum = 12345678910; char c = 'k'; char cstring[] = "This is a c-string"; string stdString = "This is a std::string"; // convert & save the above values to a std::string buffer string buffer = ToString(inum) + ", " + ToString(fnum) + ", " + ToString(lnum) + ", " + ToString(c) + ", " + ToString(cstring) + ", " + ToString(stdString); cout<<buffer<<endl; return 0; }// end of main /** * FUNCTION: ToString * USE: Converts and returns the parameter "value" to an std::string * @param value - An item of a primitive data type (int, double, long, unsigned, etc.) * @return - An std::string object containing the representation of "value" as * a sequence of characters. */ template<typename ItemType> string ToString(const ItemType& value) { stringstream convert; convert << value; return convert.str(); }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
-1987, 7.28, 12345678910, k, This is a c-string, This is a std::string