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: 123


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 if(in != 0) 34 { 35 j = int(log10(in)); 36 e = unsigned(pow(10, j)); 37 } 38 else 39 { 40 j = 0; 41 } 42 43 //now j is the number of places needed for the full representation (numbers and sign) 44 j += i; 45 46 for(k=i; k<j; k++) 47 { 48 n = in; 49 n /= e; 50 in -= n*e; 51 e /= 10; 52 53 out[k] = char(n + 48); 54 } 55 56 out[k] = char(in + 48); 57 58 out[++j] = '\0'; //set null terminator 59 60 return j; 61 } 62 63 #include <string> 64 65 std::string itoa(int in, bool showpos = false) 66 { 67 char x[9]; 68 69 itoa(in, x, showpos); 70 71 std::string s = x; 72 73 return s; 74 } 75 76 /* 77 #include <stdlib.h> 78 #include <fstream.h> 79 80 int main(void) 81 { 82 int i, j; 83 char ci[100]; 84 85 for(i=-2147483647; i<2147483647; i++) 86 { 87 itoa(i, ci); 88 89 // cout << i << "\t" << ci << "\t" << atoi(ci) << "\n"; 90 91 if(atoi(ci) != i) 92 { 93 cout << "ERROR: " << i << "\t" << ci << "\t" << atoi(ci) << endl; 94 cin >> j; 95 } 96 } 97 98 return 0; 99 } 100 */

No comments avaiable

Add a comment

Name *  

Email (won't be displayed) *    

Website  

Comment *  

Sicherheitscode Security Code *    

RSS