Jump to content

convert integer into string...

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
veda87

veda87

    Programmer

  • Members
  • PipPipPipPip
  • 126 posts
I have to convert integer to string... So I tried itoa function.. but it gave me an error
veda@veda-desktop:~$ gcc eg.c 

/tmp/ccAewlWm.o: In function `main':

eg.c:(.text+0x51): undefined reference to `itoa'

eg.c:(.text+0x7e): undefined reference to `itoa'

eg.c:(.text+0xab): undefined reference to `itoa'

collect2: ld returned 1 exit status

when I compiled with g++, it showed
veda@veda-desktop:~$ g++ eg.c 

eg.c: In function ‘int main()’:

eg.c:10: error: ‘itoa’ was not declared in this scope

I have used stdlib.h header file
what is the problem.. Or should I have write a seperate code to do this operation...

#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
You COULD write your own itoa function, depending on it's implementation that'd probably be a bit more efficient... or you can do it the super cheap way.

If you're using C++ (which judging by your g++ call, I'd say you were), use a std::stringstream. Give stringstream a number, then return the std::string value, like so:
 inline std::string stringify(double x)
 {
   std::ostringstream o;
   if (!(o << x))
     throw BadConversion("stringify(double)");
   return o.str();
 } 
OR, if you're using C, go with sprintf:
char* itoa(int num) {
    char* retstr = calloc(12, sizeof(char));
    if (sprintf(retstr, "%i", num) > 0) {
        return retstr;
    } else {
        return NULL;
    } // NOTE: You'll have to free the char pointer after this operation.
}

Wow I changed my sig!

#3
psam

psam

    Learning Programmer

  • Members
  • PipPipPip
  • 34 posts
Maybe you forgot the last function's parameter. You have to declare the integer, the string and then the base. More info here: itoa - C++ Reference.

#4
dcs

dcs

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 775 posts

psam said:

More info here: itoa - C++ Reference.

Quote

Portability
This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers.
itoa is not necessarily there, so I'd choose one of the standard methods presented earlier.

#5
theonejb

theonejb

    Learning Programmer

  • Members
  • PipPipPip
  • 52 posts
If you use C++, its advisable to use the string stream object. Its much more verastile and allows conversion between a number of standard data types.