You're here: Snippet Directory » C/C++ (495)
Language:

itoa function

Language: English
Programming Language: C++
Published by: ergeorge [not registered]
Last Update: 5/15/2006
Views: 137


Description

This function takes an integer value and returns a null-terminated C-style string. A wrapper function returns a C++ string. The full range of positive & negative integers is supported and testable via the included test program.I initially wrote this for appending run-numbers to output data file names.

Code

1 2 //This function converts an integer value to its null-terminated string representation 3 //There is also a wrapper function to return a string. 4 //I initially created this class to add numeric tags to output data file names. 5 // 6 //showpos controls whether the '+' symbol is included for positive values 7 //the default is not to show '+' 8 // 9 //return value is the number of places used in the representation 10 11 #include <math.h> 12 13 unsigned itoa(int in, char out[], bool showpos = false) 14 { 15 unsigned i, j, k, n, e; 16 17 //i indicates where the numeric representation starts 18 //This if statement places '-' and '+' signs as appropriate 19 //and sets i accordingly 20 i = 0; 21 if(in < 0) 22 { 23 out[0] = '-'; 24 i = 1; 25 in = -in; 26 } 27 else if(showpos) 28 { 29 out[0] = '+'; 30 i = 1; 31 } 32 33 j = int(log10(in)); 34 35 e = unsigned(pow(10, j)); 36 37 //now j is the number of places needed for the full representation (numbers and sign) 38 j += i; 39 40 for(k=i; k<j; k++) 41 { 42 n = in; 43 n /= e; 44 in -= n*e; 45 e /= 10; 46 47 out[k] = char(n + 48); 48 } 49 50 out[k] = char(in + 48); 51 52 out[++j] = '\0'; //set null terminator 53 54 return j; 55 } 56 57 #include <string> 58 59 std::string itoa(int in, bool showpos = false) 60 { 61 char x[9]; 62 63 itoa(in, x, showpos); 64 65 std::string s = x; 66 67 return s; 68 } 69 70 /* 71 #include <stdlib.h> 72 #include <fstream.h> 73 74 int main(void) 75 { 76 int i, j; 77 char ci[100]; 78 79 for(i=-2147483647; i<2147483647; i++) 80 { 81 itoa(i, ci); 82 83 // cout << i << "\t" << ci << "\t" << atoi(ci) << "\n"; 84 85 if(atoi(ci) != i) 86 { 87 cout << "ERROR: " << i << "\t" << ci << "\t" << atoi(ci) << endl; 88 cin >> j; 89 } 90 } 91 92 return 0; 93 } 94 */

No comments avaiable

Add a comment

Name *  

Email (won't be displayed) *    

Website  

Comment *  

Sicherheitscode Security Code *    

RSS