-
May 4th, 2004, 03:15 PM
#1
Senior Member
converting an int to a string in C
Hello: I hate strings in C. I have three int values that correspond to minutes, seconds and milliseconds, which I obtained using gettimeofday(). My problem is that I want to concatenate this values into a neatly readable string of the form: min:secs:msecs
This can be easily done in vb by just adding the strings, example: (my vars are named min, secs and msecs)
min+":"+secs+":"msecs See what I mean??
Since there isn't really a string type in C, just arrays of chars, what can I do?? I know there are functions like atoi() to convert ASCII to integer, but is there a reverse one.
I dont want to use:
printf("time: %d : %d : %d\n", min, sec, msec);
I want something like:
printf("%s\n", timestring);
thanks,
J
-
May 4th, 2004, 05:23 PM
#2
This is fairly straight forward. Your code would go something like this:
Code:
#include <stdio.h>
#include <stdlib.h>
void main()
{
int min,secs,msecs;
char temp[5],timestring[12]="";
itoa(min,temp,10);
strcat(timestring,temp);
strcat(timestring,":");
itoa(secs,temp,10);
strcat(timestring,temp);
strcat(timestring,":");
itoa(msecs,temp,10);
strcat(timestring,temp);
printf("%s",timestring);
}
One of the major problems with C is that it doesn't have string datatype. Other languages, including VB, Java and even C++ have one.
Cheers,
cgkanchi
-
May 8th, 2004, 06:19 AM
#3
Senior Member
cgkanchi:
thanks for the code, but what compiler do I have to use to make it work. I am using gcc on MacOsX and got the following error:
gcc -o u untitled.c
ld: Undefined symbols:
_itoa
I looked into stdlib.h and there is no definition for itoa(); what can I do??? Is my library wrong or what??
cheers,
J
-
May 8th, 2004, 09:11 AM
#4
Hi
johnnymier no your library is not wrong or incomplete . In future try to mention compiler and OS you would be using because many functions are not portable the code cgkanchi gave will work fine on Turbo C, VC++ , Quick C etc on Windows plateform. In GCC ltoa are not standard you would have to use Either use sprintf() or something hand-made
and sorry i have only worked with TUrbo C and VC++ so i can't help you hope somebody will port it for you .
--Good Luck--
-
May 8th, 2004, 02:26 PM
#5
Oh crap! I didn't know that this wasn't a standard C function. Gimme a sec and I'll hack something up. Wait a sec... I tried this on GCC under Windows and it works. There's no reason it shouldn't work. However, I'll post something as soon as I hack it up.
EDIT: From here,
Portability.
Not defined in ANSI-C. Supported by some compilers.
EDIT: Crap! I'm forgetting my ANSI-C. This is what you need:
Code:
char number_str[10];
int number = 25;
sprintf(number_str, "%d", number);
From here
Cheers,
cgkanchi
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
|