CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7
  1. #1
    Join Date
    Jun 1999
    Location
    SLC, Utah
    Posts
    155

    int to char* conversion

    Does anybody know of any standard C++ functions to convert an int to a char*?

    Something that would take the number 9876 to {'9','8','7','6'}?

    I would rather not reinvent the wheel if there is something like this already.

    Thanks,
    Brian Budge


  2. #2
    Join Date
    Jun 1999
    Location
    Canada - Québec
    Posts
    273

    Re: int to char* conversion

    u can use itoa();



  3. #3
    Join Date
    May 1999
    Location
    CA
    Posts
    188

    Re: int to char* conversion

    This isn't C++ specific, but...


    int integer=9876;
    char string[20]; // be big enough for the digits

    sprintf(string,"%d",integer);

    // string now contains "9876"






  4. #4
    Join Date
    May 1999
    Location
    Seattle, WA USA
    Posts
    423

    Re: int to char* conversion

    The original poster was asking for a standard C++ function to convert an int to a char*, and _itoa is not standard, it is Microsoft specific. Some other compilers may support it, but it is not part of the standard library. If Brian Budge is only interseted in the Windows platform, itoa is fine, but it is not standard.

    The more portable way to do this is as Eric Smith said, sprintf.

    HTH
    --michael

  5. #5
    Join Date
    Jun 1999
    Location
    Canada - Québec
    Posts
    273

    Re: int to char* conversion

    yes .. its true.. i anwsered too fast..



  6. #6
    Join Date
    Jul 1999
    Posts
    3

    Re: int to char* conversion

    You can do:
    char *str;
    int nValor=9876;
    str = new char ;
    wsprintf(str,"%d",nValor);
    Hope this help.
    Leila


  7. #7
    Join Date
    May 1999
    Location
    Seattle, WA USA
    Posts
    423

    Re: int to char* conversion

    you wouldn't want to do that. You are only allocating 1 byte, and then trying to write a 5 byte string into it. you would have to new a char array big enough to hold all the numbers.
    str = new char [5]; // atleast 5.
    and then delete it later. Of course if the length is constant
    char str[5]
    is better.

    HTH
    --michael

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured