Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I convert Integer to String

Status
Not open for further replies.

SGLong

Programmer
Jun 6, 2000
405
US
I need to make an adjustment to an old ANSI C application. The original programmer is no longer with us and nobody here has experience with C.

I have an integer value (numofgroups) that I want to convert to a string value (pie_count). I know that there is a 'sprintf' function, but the documentation is extremely poor as to how to call the function. I've tried several variations of this function but keep getting compile errors.

Any suggestions would be greatly appreciated.
 
int numofgroups = 2001;
char buf[256];
sprintf(buf, "%d", numofgroups);
cout << buf << endl;

Hope this helps
-pete
 
@palbano

cout is C++; It's not possibel with ANSI C.

Use printf instead.

e.g. printf(&quot;%s\n&quot;,buf);
 
@thebigf,

uh... ooops, my bad.
Thanks for watching my back. B-)

-pete
 
TO convert a string into integer, you could use itoa function. It is found stdlib.h file.
Similarly atoi will convert a string into an integer.

Hope this helps!

Sriks
 
Sriks,

That's what I was looking for... thanks

Steve
 
if u must,

int length, i, j;
char buf[15];
num=numofgroups;
length=log10(num)+1; /*this can be leave one leading byte with a zero in it.*/
memset(buf,'0',15);
for (i=0,j=length; i<length;i++)
{
buf[--j]=num%10;
num /= 10;
}
buf=0;

printf(&quot;\nnow is %d == %s ??\n&quot;, numofgroups, buf);

hth,
shail.
 
Why such complicated?

try:

sprintf(buffer,&quot;%-d&quot;,value);

hnd
hasso55@yahoo.com

 
A revised version based on shail's (tested).

int length, i;
char buf[15];
int num = n;
length=(int)log10(n)+1;
memset(buf,'0',15);
buf[length] = 0;
for (i=length-1; i >= 0;i--)
{
buf += num%10;
num /= 10;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top