1 /////////////////////////////////////////////////////////////////////////
2 // ftoa.cpp
3 //
4 // Copyright (c) 1996-2003 Bryce W. Harrington [bryce at osdl dot org]
5 //
6 //-----------------------------------------------------------------------
7 // License: This code may be used by anyone for any purpose
8 // so long as the copyright notices and this license
9 // statement remains attached.
10 //-----------------------------------------------------------------------
11 //
12 // This routine converts an integer into a string
13 //
14 /////////////////////////////////////////////////////////////////////////
16 // Standard include files
17 #include <algorithm>
18 #include <string> // for string
19 #include <cstring>
21 using namespace std;
23 string itos(int n)
24 {
25 int sign;
26 string s;
28 if ((sign = n) < 0) // record sign
29 n = -n; // make n positive
30 do { // generate digits in reverse order
31 s += (char(n % 10) + '0'); // get next digit
32 } while ((n/=10) > 0); // delete it
34 if (sign < 0)
35 s += '-';
37 reverse(s.begin(), s.end()); // This is what the code should look like
38 // if the string class is compatible with
39 // the standard C++ string class
40 #ifdef DUMB_OS_LIKE_WINDOWS
41 // In Windows, we'll use this hack...
42 for (int i=0, j=s.GetLength()-1; i<j; i++, j--)
43 {
44 char c = s[i];
45 // s[i] = s[j];
46 // s[j] = c;
47 s.SetAt(i, s[j]);
48 s.SetAt(j, c);
49 }
50 #endif
52 return s;
53 }
55 string ultos(unsigned long n)
56 {
57 string s;
59 do { // generate digits in reverse order
60 s += (char(n % 10) + '0'); // get next digit
61 } while ((n/=10) > 0); // delete it
63 reverse(s.begin(), s.end()); // This is what the code should look like
64 // if the string class is compatible with
65 // the standard C++ string class
66 #ifdef DUMB_OS_LIKE_WINDOWS
67 // In Windows, we'll use this hack...
68 for (int i=0, j=s.GetLength()-1; i<j; i++, j--)
69 {
70 char c = s[i];
71 // s[i] = s[j];
72 // s[j] = c;
73 s.SetAt(i, s[j]);
74 s.SetAt(j, c);
75 }
76 #endif
78 return s;
79 }