One of the first issues I encountered when learning C++ was that the itoa
function was supported on some compilers but was not actually defined in the ANSI-C standard (and therefore was generally considered bad practice to use).
I have seen multiple solutions such as using stringstream
or snprintf
, which have always felt very roundabout to me, and finally in C++11 there is std::to_string
which feels much cleaner from a language perspective.
But why did it take so long for a more direct method to be added? I have had trouble finding anything beyond some discussions of efficiency and lack of desire to change the standard without good reason. Was anything ever officially stated on why this was not included or why they finally decided to add it in C++11? Has there been any discussion of adding this to a future revision of C?
In hindsight, it was an oversight. However, without knowing details about the development history of C++, I’d venture the guess that this oversight has good reasons, rooted in theory. See, a conversion from number to string and vice versa is far from trivial, and it doesn’t fit the normal definition of a “cast” very well (in reality, it requires a parser / formatter), even though most other languages do provide such a cast.
Added to that is the fact that C++’ support for string types is rather … pedestrian. C doesn’t even have a real, dedicated type for it, it uses
char
arrays instead. C++ goes slightly further but stops well short of proper built-in string support. This can be seen in many aspects, from the fact that the string literal is still a null-terminatedchar
array, to the broad consensus thatstd::string
has a bloated, poorly designed interface. And don’t forget thatstd::string
doesn’t even represent a string! It represents an array of bytes! This is an important distinction, and the reason for this is simply thatstd::string
is completely encoding agnostic.Ah, but C++ actually does support proper encoding, and proper parsing and formatting. It simply doesn’t provide it for strings – it provides it for streams.
And there we have it. C++ has no proper string type. Instead, it has input/output streams.