itoa???

This is a discussion on itoa??? within the C++ Programming forums, part of the General Programming Boards category; How would I convert an int to a character string? ex... int number = 534; char str[4] = {some funtion ...

  1. #1
    Registered User
    Join Date
    Dec 2001
    Posts
    17

    itoa???

    How would I convert an int to a character string? ex...

    int number = 534;
    char str[4] = {some funtion here}(number);
    -----------------------
    R. D. Nichols, Jr.

    -Why do I have to go EVERYWHERE in this handbasket?

  2. #2
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,386
    You could use sprintf() for this.

    http://www.f.kth.se/~f95-pax/refs/C%...o.html#sprintf

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >How would I convert an int to a character string?
    There are two standard and portable options:
    Code:
    #include <iostream>
    #include <sstream>
    #include <cstdio>
    
    int main()
    {
      int i = 12345;
    
      // The C way
      char a[6];
    
      sprintf ( a, "%d", i );
      std::cout<< a <<std::endl;
    
      // Or the C++ way
      std::ostringstream oss;
    
      oss<< i;
      std::string s = oss.str();
    
      std::cout<< s <<std::endl;
    }
    -Prelude
    My best code is written with the delete key.

  4. #4
    Registered User
    Join Date
    Dec 2001
    Posts
    17
    Thanks guys. Both ways work.
    -----------------------
    R. D. Nichols, Jr.

    -Why do I have to go EVERYWHERE in this handbasket?

  5. #5
    Senior Member joshdick's Avatar
    Join Date
    Nov 2002
    Location
    Phildelphia, PA
    Posts
    1,146
    I prefer to write my own functions. This will work for positive integers. Making it work for negatives, too, wouldn't be difficult.
    Code:
    char* IntToA(int num)
    {
    	char* strNum;
    	int sameNum = num;
    	int length = 0;
    	while(sameNum)
    	{
    		sameNum /= 10;
    		++length;
    	}
    	strNum = new char[length];
    	int i = 1;
    	while(num)
    	{
    		strNum[length - i] = num % 10 + '0';
    		num /= 10;
    		++i;
    	}
    	return strNum;
    }
    Are there any reasons why one shouldn't use my function as opposed to the other methods suggested?
    FAQ

    "The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs." -- Joseph Weizenbaum.

    "If you cannot grok the overall structure of a program while taking a shower, you are not ready to code it." -- Richard Pattis.

  6. #6
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,386
    >I prefer to write my own functions.

    So, you rewrite the standard library when programming? It is a good excercise, but in projects, I prefer to reuse already tested code.

    >Are there any reasons why one shouldn't use my function as
    >opposed to the other methods suggested?

    Portability: if I would use your function and then use the code on a different platform, I would also have to recompile your functions on that platform and hope that they work as they did on the first platform.

  7. #7
    Senior Member joshdick's Avatar
    Join Date
    Nov 2002
    Location
    Phildelphia, PA
    Posts
    1,146
    Originally posted by Shiro
    >I prefer to write my own functions.

    So, you rewrite the standard library when programming? It is a good excercise, but in projects, I prefer to reuse already tested code.
    Yeah, not only is it a good exercise, it's fun too And, I'll have you know that I tested my function

    >Are there any reasons why one shouldn't use my function as
    >opposed to the other methods suggested?

    Portability: if I would use your function and then use the code on a different platform, I would also have to recompile your functions on that platform and hope that they work as they did on the first platform.
    I don't see why my function wouldn't work on another platform. I didn't need to include anything except <iostream> to run it, and I didn't use any compiler specific code.
    FAQ

    "The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs." -- Joseph Weizenbaum.

    "If you cannot grok the overall structure of a program while taking a shower, you are not ready to code it." -- Richard Pattis.

  8. #8
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >I prefer to write my own functions.
    This is always good when practicing, but for production code it's a waste of your time to recreate that which already exists.

    >Are there any reasons why one shouldn't use my function as opposed to the other methods suggested?
    They're standard, portable, guaranteed to work everywhere the same way, there's no reason to wonder if the logic is wrong somewhere, there's less code to check if a bug does occur, it's easier to maintain, find documentation on, read, understand... I could go on.

    >I don't see why my function wouldn't work on another platform.
    Actually, it wouldn't. Your function has a serious bug and lacks crucial functionality.

    -Prelude
    My best code is written with the delete key.

  9. #9
    Senior Member joshdick's Avatar
    Join Date
    Nov 2002
    Location
    Phildelphia, PA
    Posts
    1,146
    Originally posted by Prelude
    >I prefer to write my own functions.
    This is always good when practicing, but for production code it's a waste of your time to recreate that which already exists.
    Yeah, I know. If I was a professional programmer, I wouldn't waste my time rewriting standard functions.


    >I don't see why my function wouldn't work on another platform.
    Actually, it wouldn't. Your function has a serious bug and lacks crucial functionality.
    Ouch! I know it doesn't work for negative integers. Also, I wasn't sure if I should delete strNum at the end of the function, and if so, where to delete it. Mind telling me how to improve that function? I'm just really curious.
    FAQ

    "The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs." -- Joseph Weizenbaum.

    "If you cannot grok the overall structure of a program while taking a shower, you are not ready to code it." -- Richard Pattis.

  10. #10
    Senior Member joshdick's Avatar
    Join Date
    Nov 2002
    Location
    Phildelphia, PA
    Posts
    1,146
    Code:
    char* IntToA(int num)
    {
    	char* strNum;
    	int sameNum = num;
    	int length = 0;
    	while(sameNum)
    	{
    		sameNum /= 10;
    		++length;
    	}
    	strNum = new char[length+1];
    	int i = 1;
    	while(num)
    	{
    		strNum[length - i] = num % 10 + '0';
    		num /= 10;
    		++i;
    	}
    	strNum[length+1] = '\0';	// NULL terminated
    	return strNum;
    	delete[] strNum;	// deallocates memory
    }
    There, would that work? And, how could I make the code faster?
    FAQ

    "The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs." -- Joseph Weizenbaum.

    "If you cannot grok the overall structure of a program while taking a shower, you are not ready to code it." -- Richard Pattis.

  11. #11
    I lurk
    Join Date
    Aug 2002
    Posts
    1,361
    Originally posted by joshdick
    Code:
    char* IntToA(int num)
    {
    	char* strNum;
    	int sameNum = num;
    	int length = 0;
    	while(sameNum)
    	{
    		sameNum /= 10;
    		++length;
    	}
    	strNum = new char[length+1];
    	int i = 1;
    	while(num)
    	{
    		strNum[length - i] = num % 10 + '0';
    		num /= 10;
    		++i;
    	}
    	strNum[length+1] = '\0';	// NULL terminated
    	return strNum;
    	delete[] strNum;	// deallocates memory
    }
    There, would that work? And, how could I make the code faster?
    Nope, the function returns before the memory gets deleted.
    /me wonders why you'd return a pointer to deallocated memory anyway

  12. #12
    Senior Member joshdick's Avatar
    Join Date
    Nov 2002
    Location
    Phildelphia, PA
    Posts
    1,146
    Shoot, egg on my face. I forgot about that whole 0 to n-1 thing. Yeah, I get the point. The thing is, I don't trust standard libraries very much because I don't understand them. I've tried looking at the code for them, but I don't understand much of it. *sigh* I guess I'll give up now and use the boring standard functions
    FAQ

    "The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs." -- Joseph Weizenbaum.

    "If you cannot grok the overall structure of a program while taking a shower, you are not ready to code it." -- Richard Pattis.

  13. #13
    Registered User rmullen3's Avatar
    Join Date
    Nov 2001
    Posts
    330

    question

    Not being a master coder myself, I was wondering while on this piece of code if someone could tell me how to return the contents of strNum from the function and still delete the memory? It's probably painfully obvious but I can't figure it out =) Thanks!

  14. #14
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >Mind telling me how to improve that function?
    Your first goal should be removing the memory allocation. C++ is designed so that you can avoid such low level operations more often than you would expect. Either have the user pass in a buffer or avoid potentially dangerous char arrays and use std::string or another suitable string class that handles memory for you. Next you need to handle negative numbers, the usual solution looks like this:
    Code:
      std::string atoi ( int n )
      {
        int sign = n;
        std::string s;
    
        if ( sign < 0 )
          n = -n;
    
        do
          s += ( n % 10 ) + '0';
        while ( ( n /= 10 ) != 0 );
    
        if ( sign < 0 )
          s += '-';
    
        std::reverse ( s.begin(), s.end() );
    
        return s;
      }
    Of course if you run that on the most negative number under two's complement you don't quite get what you want, my output for this on INT_MIN is

    -./,),(-*,(

    This is a far cry from the expected

    -2147483648

    So, fixing that problem (which makes the code shorter, how nice!) and protecting against current atoi implementations on the compiler by embedding our function in a namespace brings us to this:
    Code:
    #include <algorithm>
    #include <iostream>
    #include <cstdlib>
    #include <limits>
    #include <string>
    
    namespace pre
    {
      std::string atoi ( int n )
      {
        int sign = n;
        std::string s;
    
        do
          s += std::abs ( n % 10 ) + '0';
        while ( ( n /= 10 ) != 0 );
    
        if ( sign < 0 )
          s += '-';
    
        std::reverse ( s.begin(), s.end() );
    
        return s;
      }
    }
    
    int main()
    {
      std::cout<< pre::atoi ( std::numeric_limits<int>::max() ) <<std::endl;
      std::cout<< pre::atoi ( std::numeric_limits<int>::min() ) <<std::endl;
    }
    Which could still be improved, but will work nicely for most general usage.

    >I don't trust standard libraries very much because I don't understand them.
    That's not a reason to avoid them, instead you should work to understand them. Consider this, if you don't understand the libraries that you are recreating then why do you think you can write them better?

    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem using itoa
    By g_p in forum C Programming
    Replies: 2
    Last Post: 05-03-2008, 06:38 AM
  2. Problem with itoa() perhaps?
    By TheSquid in forum C++ Programming
    Replies: 5
    Last Post: 05-08-2006, 02:04 AM
  3. Really Weird itoa Problem
    By Grantyt3 in forum C++ Programming
    Replies: 8
    Last Post: 12-19-2005, 11:44 PM
  4. itoa
    By coldcoyote in forum Linux Programming
    Replies: 4
    Last Post: 02-13-2003, 08:28 AM
  5. itoa
    By Thantos in forum C Programming
    Replies: 2
    Last Post: 09-18-2001, 02:23 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21