Differences between version 10 and revision by previous author of ConvertingAnIntegerToaStringInCpp.
Other diffs: Previous Major Revision, Previous Revision, or view the Annotated Edit History
Newer page: | version 10 | Last edited on Monday, May 15, 2006 1:13:37 pm | by CraigBox | Revert |
Older page: | version 7 | Last edited on Thursday, October 21, 2004 5:21:10 pm | by AristotlePagaltzis | Revert |
@@ -1,33 +1,40 @@
-InNeedOfRefactor
-
We seem to be getting a hit a day trying to figure out how to converting an Integer to a String in C++, so I thought I'd better write a page about it.
!!Method One: snprintf(3)
This technically gives you a char*, not a "String", but who's counting eh?
-
int i2str(int i) {
-
int i;
-
char s[[256];
-
snprintf(s,sizeof(s),"%i",i);
-
return strdup(s);
- }
+<verbatim>
+
int i2str(int i) {
+ int i;
+ char s[[256];
+ snprintf(s,sizeof(s),"%i",i);
+ return strdup(s);
+}
+</verbatim>
!!Method Two: use a stringstream
-
#include <sstream>
- #include <string>
+<verbatim>
+
#include <sstream>
+#include <string>
-
std::string i2string(int i) {
-
std::ostringstream buffer;
-
buffer << i;
-
return buffer.str();
- }
+std::string i2string(int i) {
+ std::ostringstream buffer;
+ buffer << i;
+ return buffer.str();
+}
+</verbatim>
or:
+
!!Method Three: Anything to string
-
template<class T>
- std::string any2string(T i) {
-
std::ostringstream buffer;
-
buffer << i;
-
return buffer.str();
- }
+<verbatim>
+
template<class T>
+std::string any2string(T i) {
+ std::ostringstream buffer;
+ buffer << i;
+ return buffer.str();
+}
+</verbatim>
+
+CategoryProgramming