Wednesday, April 16, 2008

Convert Integer to String

Program convert an integer to string
/****
function that converts an integer into a string
representing of that integer....
[integer can start with an optional + or - sign]

intTOstring1() - uses while loop (need reverse() to
reverse the string

intTOstring2() - uses recursion ( don't need to reverse )

example
char s[100];
intTOstring(-134234, s);
printf(s);
output: -134234
****/

//This function uses recursion to convert integer to string
void intTOstring2(int x, char *s)
{

static int i = 0;
if (x < 0)
{

s[i++] = '-';
x = -x;
}
if ( x/10 )
{

intTOstring2( x/10, s );
}
s[i++] = x%10 + '0';
s[i] = '\0';
}

//This function uses a while loop to convert integer to string
//This function will then call reverse() function to reverse the string
void intTOstring1(int x, char *s)
{

int isNegative = 0,tmp;
char *p = s,*t = s,tmp1;
if( x == 0 )
{

*s = '0';
*(s+1) = '\0';
return;
}

if ( x < 0 )
{

isNegative=1;
x*=-1;
}

//keep dividing by 10 and collect each digit
while ( x > 0 )
{

tmp = x%10;
*p++ = tmp+'0';
x /= 10;
}
if( isNegative )
*p++ = '-';
*p = '\0';
}

//reverse the string
void reverse( char *s )
{

char *p = s,*t = s,tmp;

while ( *p )
p++;
while ( t < p )
{

tmp = *t;
*t++ = *--p;
*p = tmp;
}
}

10 comments:

sridotc said...
This comment has been removed by the author.
sridotc said...
This comment has been removed by the author.
KBS said...

You need to modify the blog such that indents are not trimmed.

sridotc said...

hmm well that brings up another point in order for me to put tab, I have to go to each line I want to tab and do this < blockquote > < / blockquote >

Now I am thinking of writing a program that will do this. Thats my next task.

KBS said...

sridotc,

Why don't you use an editor that will put 4 spaces when you hit tab?

Can't this blog support spaces?

sridotc said...

nope, spaces not supported

KBS said...

Can you make your program convert the spaces that would be deleted by < br > in html?

sridotc said...

Right now blockquote is adding extra lines

Here is a version of the intTOstring which uses recursion

void intTOstring2(int x, char *s)
{
static int i = 0;
if (x < 0)
{
s[i++] = '-';
x = -x;
}
if ( x/10 )
{
intTOstring2( x/10, s );
}
s[i++] = x%10 + '0';
s[i] = '\0';
}

KBS said...

Did you test that function?

You're testing must be weak.

I can tell by looking at it that it will fail if I do:

char buf1[10], buf2[10], buf3[10], buf4[10]={0};

intTOstring2(45, buf1);
intTOstring2(-123, buf2);
intTOstring2(2329, buf3);

printf("%s %s %s\n", buf1, buf2, buf3);

sridotc said...

If called several time, the static variable never get reset.

Is that what you meant?

Then, I get it, it will not work for subsequent calls.