home   articles   tags   browse code   

C++ itoa function


 

While the stdlib defines an itoa function, it uses c strings, and takes a base parameter. I wanted to make a function that did not depend on the stdlib, and works on stl strings, works in base10 and only requires an integer as its parameter.

I also included a second itoa function below (itoa1), but it uses a less efficient operation of putting the string together despite doing it all in one pass.
#include <iostream>
#include <string>

using namespace std;

string itoa(const int &integer);
string itoa1(const int &integer);

int main(int argc, char *argv[])
{
    cout <<"["<<itoa(0)<<"]"<<endl;
    cout <<"["<<itoa(1)<<"]"<<endl;
    cout <<"["<<itoa(9)<<"]"<<endl;
    cout <<"["<<itoa(10)<<"]"<<endl;
    cout <<"["<<itoa(11)<<"]"<<endl;
    cout <<"["<<itoa(20)<<"]"<<endl;
    cout <<"["<<itoa(99)<<"]"<<endl;
    cout <<"["<<itoa(100)<<"]"<<endl;
    cout <<"["<<itoa(101)<<"]"<<endl;
    cout <<"["<<itoa(123456789)<<"]"<<endl;
    cout <<"["<<itoa(2123456789)<<"]"<<endl;
    cout <<"["<<itoa(-1)<<"]"<<endl;
    cout <<"["<<itoa(-2)<<"]"<<endl;
    cout <<"["<<itoa(-2123456789)<<"]"<<endl;
    return 0;
}

string itoa(const int &integer)
{
    if (integer==0) return string("0");

    string a;
    int start, digits, piece;

    //count digits
    digits=0;
    piece=((integer<0)? 0-integer : integer);
    while( piece > 0 )
    {
        piece-= (piece%10);
        piece/=10;
        digits++;
    }

    start=((integer<0)? 1 : 0);
    a.resize(digits+start,' ');//this makes append() not have to allocate new memory
    if (integer<0) a[0]='-';

    piece=((integer<0)? 0-integer : integer);
    for(int i=0;  piece > 0; i++ )
    {
        a[ digits+start-i-1] = (piece%10)+48;
        piece-= (piece%10);
        piece/=10;
    }

    return a;
}

string itoa1(const int &integer)
{
    if (integer==0) return "0";

    char buf[2]={0,0};
    string a;
    int piece=integer;
    if (integer<0)
        piece *=-1;

    while( piece > 0 )
    {
        int digit=piece%10;
        piece-=digit;//unnecessary cause the next line will do integer division
        piece/=10;//shift to right

        buf[0] = digit+48;//int to char digit
        a = string(buf) + a;//not an efficient process
    }

    if (integer<0)
        a= "-" + a;

    return a;
}
 

Tags: c++
 
chris on Mar 10th, 2011 8:10 am said:
Total nonsense. I bookmarked this website and the others in code-review-department are all on maximum ROFL.
 



 

 



Related Articles
 


home  |  privacy policy  |  terms of use  |  contact  


©2012, Zedwood.com

zedwood.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to amazon.com