Monday 14 January 2013

std::to_string()

Starting simple, I was really pleased and a little surprised to see to_string (and its sibling, to_wstring) pop up. It's a feature that we've really needed for more time than I care to consider and it removes the need for the fairly foul: 

 char buff[12] = {0};  
 sprintf(buff, "%d", INT_MIN);  
 /* convert to std::string if we like */  

or the moderately foul:


 std::ostringstream mystream;  
 mystream << INT_MIN;  
 std::string s = mystream.str();  

I'm not saying there aren't proper uses for sprintf or stringstream, it's just that the above seems such a waste of time when you consider Python's str() or even C#'s versatile Convert.ToString(). Neither of my examples are very expressive and the first gets even worse if you're developing for a Microsoft platform and you have to start considering sprintf_s and the like.

std::to_string is long overdue and extremely simple to use:


 float f = 3.14;  
 std::string piString = std::to_string(f);  

What could be easier than that? No worrying about buffer sizes, no baroque format string incantations, no stringstream wastes. That ends the first real post. If anyone posts comments, I promise to read them. Is anybody out there?

1 comment:

  1. Also worth noting that there are now conversion functions to go the other way, such as std::stoi() and std::stof()

    ReplyDelete