May 4th, 2004, 04:15 PM
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:
May 4th, 2004, 06:23 PM
This is fairly straight forward. Your code would go something like this:
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.
May 8th, 2004, 07:19 AM
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:
I looked into stdlib.h and there is no definition for itoa(); what can I do??? Is my library wrong or what??
gcc -o u untitled.c
ld: Undefined symbols:
May 8th, 2004, 10:11 AM
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 .
May 8th, 2004, 03:26 PM
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,
Not defined in ANSI-C. Supported by some compilers.
EDIT: Crap! I'm forgetting my ANSI-C. This is what you need:
int number = 25;
sprintf(number_str, "%d", number);