Sunday, 1 January 2012

C++ programming Getting rid of sprintf()

like the name, I suspect the function "sprintf()" is very fast, but for the sake of non-programmers I am going to explain what it does.

http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/

so if I want to format a block of text into a buffer with numbers I can use sprintf(). The only problem is with the safety of using sprintf, the convenience of allocating an array of bytes in memory every time I want to make some text

Well now (and for a very long time since the creation of the C++ std library) there is a safer and less buggy solution, that also makes the code look a lot neater. Its called "crawls()" ... just kidding.

Now I use this function


template <class T>
inline std::string to_string (const T& t)
{
std::stringstream strStream;
strStream<< t;
return  strStream .str();
}

this turns the number into a string without all the old-style conditional statements.

No comments:

Post a Comment