C++ Integer to String function

mvmalderen 0 Tallied Votes 1K Views Share

I've written a C++ function which converts an integer to a (C++-)string ...

...
string s = itos(5698);
cout << s << endl; /* Will print '5698' on the screen */
...

You MAY use this code for anything you want but you aren't allowed to sell this source ...

Enjoy!

tux4life

/*****************************************
* Written by Mathias Van Malderen 
* Copyright (c) 2009 Mathias Van Malderen
******************************************/


/***************************
	itos(int a)
****************************/

string itos(int a)
{
    /* Convert an integer to a string */
    int b = 0, c = 1, n = 0;
    string result;

    while(apow(10,n) < a) n++;
	
    if(n != 0) n--;
    b = apow(10,n);

    while((b*c) < a) c++;

    if(n != 0) c--;
    a -= (b*c);
    result += digit2str(c);
    if(n != 0) result += itos(a);

    return result;
}

/***************************
	DEPENDENCIES
****************************/

int apow(const int &x, int y)
{
    /* Raise x to the power of y */
    int result = 1;
    if(y < 0)
	return apow(1/x, -y);
    for(int i = y; i > 0; i--)
	result *= x;
    return result;
}

string digit2str(short digit)
{
    /* Convert a digit to a string */
    string tmp;
    if(digit >= 0 && digit <= 9)
    {
        tmp = digit + '0';
        return tmp;
    }
    return "";
}
ShawnCplus 456 Code Monkey Team Colleague

Actually there is a standard method to do this using C++ string streams

int some_int = 10;
stringstream some_stream;
some_stream << some_int;
string some_string = some_stream.str();
mvmalderen 2,072 Postaholic

I know you can achieve the same using string streams, but my goal was to do without ...

Still thanks for your reply !

William Hemsworth 1,339 Posting Virtuoso

A bit of an overkill don't you think? Also, your function can't handle negative numbers, mine can :D

string itos(int a) {
  if ( a == 0 )
    return "0";
  int sign = (a < 0 ? a = -a, 1 : 0);
  string result = sign ? "-" : "";
  char temp;
  while ( a ) {
    temp = '0' + a % 10;
    result.insert( sign, &temp, 1 );
    a /= 10;
  }
  return result;
}
mvmalderen 2,072 Postaholic

Yeah, you're right William, but I was planning to rewrite the whole code for the reason you mentioned ...
My fixed code would also have used the modulo operator
(in that way I can finally get rid of that apow-function :P)

Nice to know is that I actually forgot to make it 'negative number'-friendly, thanks for mentioning that :) !!

mvmalderen 2,072 Postaholic

Here's the final code of my itos-function, and you can see that I've completely rewritten it :) :

string itos(int a) {
	string sign = a<0?"-":"";
	string result = a>0?string(1,(a%10+'0')):string(1,((a=-a)%10+'0'));
	(a/=10)>0?result=itos(a)+result:result;
	return sign+result;
}

The ternary operator is my friend :P !!!

mvmalderen 2,072 Postaholic

It works but I think it isn't very understandable anymore :P ...

ztdep -8 Junior Poster in Training

A bit of an overkill don't you think? Also, your function can't handle negative numbers, mine can :D

string itos(int a) {
  if ( a == 0 )
    return "0";
  int sign = (a < 0 ? a = -a, 1 : 0);
  string result = sign ? "-" : "";
  char temp;
  while ( a ) {
    temp = '0' + a % 10;
    result.insert( sign, &temp, 1 );
    a /= 10;
  }
  return result;
}

Dear friends:
Could you please tell me what is the meaning of "&temp" in the result.insert.
i can not understand it.
Regards.

sergent 52 Posting Pro

You MAY use this code for anything you want but you aren't allowed to sell this source

Hello, if anyone interested, I am selling the source code of a function that converts integer to a C++ string (just kidding :p)

raptr_dflo 48 Posting Pro

temp is defined as type char at line 6. result is an instance of class string . There is no string.insert() method variant that takes a char argument, so the author used

string& insert ( size_t pos1, const char* s, size_t n);

which takes an array of characters (or a pointer to a character, same thing in C/C++) and a length (in case the character array or string, same thing in C) is not null-terminated. He is then passing a pointer to the character temp , which he creates by using the address-of operator & . Since he doesn't have a null-terminated array of characters, he also passes 1 to indicate that the "string" is just the one character in length.

mvmalderen commented: Great explanation :) +14
ztdep -8 Junior Poster in Training

temp is defined as type char at line 6. result is an instance of class string . There is no string.insert() method variant that takes a char argument, so the author used

string& insert ( size_t pos1, const char* s, size_t n);

which takes an array of characters (or a pointer to a character, same thing in C/C++) and a length (in case the character array or string, same thing in C) is not null-terminated. He is then passing a pointer to the character temp , which he creates by using the address-of operator & . Since he doesn't have a null-terminated array of characters, he also passes 1 to indicate that the "string" is just the one character in length.

thank you very much. I got it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.