Differences between version 9 and previous revision of ConvertingAnIntegerToaStringInCpp.
Other diffs: Previous Major Revision, Previous Author, or view the Annotated Edit History
Newer page: | version 9 | Last edited on Monday, May 15, 2006 1:13:17 pm | by CraigBox | Revert |
Older page: | version 8 | Last edited on Monday, May 15, 2006 1:12:22 pm | by CraigBox | Revert |
@@ -2,32 +2,37 @@
!!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);
+}
!!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();
+}
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