Trouble creating function to convert an int directly into std::string


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 9 of 9

Thread: Trouble creating function to convert an int directly into std::string

  1. #1
    Join Date
    Sep 2009
    Posts
    3

    Trouble creating function to convert an int directly into std::string

    I am trying to create a function to convert an int directly into a std::string. I know there are functions that can convert an int into c style strings, but the conversions from c_style strings kept mucking up my code and making it confusing, so i decided that this would be a better option.

    So far I have been successful except for in the case of digits with the value of 0. The function just drops 0's right out of the string. The reason for this is because my function works by subtracting off a digit at a time. So for example, it would take 635 and subtract 600 and then put 35 back into the loop. But if the number has '0' digits like 603, it would subtract off the 600 and leave 3, so it doesn't even process the tens place.

    I'm basically just looking for a clever way to put my zeros back in without the code becoming too big. I am also not worried about converting negative values.

    I have included a short demo below along with the function for you to mess with. Any help is appreciated. Thank you. =D

    Code:
    #include <iostream>
    #include <string>
    
    std::string Int_To_String(int n);
    
    int main(int argc, char *argv[])
    {
        int n;
        std::cout<<"enter an int: ";
        std::cin>>n;
        while (n>=0)
        {
            std::cout<<std::endl<<"here: "<<Int_To_String(n)<<std::endl;
            std::cout<<"enter an int: ";
            std::cin>>n;
        }
        std::cout<<std::endl;
        system("PAUSE");
        
    }
    
    std::string Int_To_String(int n)
    {
        int temp, power;
        std::string str;
        str="";
        temp=n;
        do
        {
            for(power=0; temp>=10; power++)
            {
                temp/=10;
            }
            str=str+char((int('0')+temp));
            for(power; power>0; power--)
            {
                temp*=10;
            }
            n-=temp;
            temp=n;
        } while(n>0);
        return str;
    }

  2. #2
    Join Date
    Nov 2003
    Posts
    4,118
    Th easiest way to do that C++ style is to use the <sstream> library: http://www.builderau.com.au/program/...0272027,00.htm
    Danny Kalev

  3. #3
    Join Date
    Oct 2007
    Posts
    369
    Here's an old gem I learned ages ago. Any object for which operator<< is defined for ostream (that includes anything that you can output with cout)

    #include <iostream>
    template<typename T>
    std::string toString(const T& t)
    {
    ostream ostr;
    ostr << t
    return ostr.str();
    }

  4. #4
    Join Date
    Oct 2007
    Posts
    369
    Oops. That wasn't quite right:
    Code:
    #include <sstream>
    template<typename T>
    std::string toString(const T& t)
    {
        ostringstream str;
        ostr << t;
        return ostr.str();
    }

    I thought I'd give the inverse function as well:

    Code:
    #include <iostream>
    template<typename T>
    void fromString(std::string s, T& t)
    {
       sstream str(s);
       str >> t;
    }

  5. #5
    Join Date
    Oct 2007
    Posts
    369
    Now the second one wasn't quite right
    Code:
    #include <iostream>
    template<typename T>
    void fromString(std::string s, T& t)
    {
       istringstream str(s);
       str >> t;
    }

  6. #6
    Join Date
    Sep 2009
    Posts
    3
    Oh wow. I didn't even know something like that existed =D. I did manage to come up with my own solution though. I had been starting at the left and working right, but I thought about it and noticed something. If you start right and then go left along a number the zeroes have to stay in place as placeholders. So my answer: modulus.

    Code:
    std::string Int_To_String(int n)
    {
        int temp;
        std::string str1, str2;
        str1="";
        str2="";
        temp=n;
        do
        {
            temp&#37;=10;
            str1=str1+char(int('0')+temp);
            str2=str1+str2;
            str1="";
            n/=10;
            temp=n;
        } while(n>0);
        
        return str2;
    }
    This function works perfectly, but i think I'll use the <sstream> method because this still doesn't support negative numbers which I may or may not need in my project as it progresses. Thank you.

  7. #7
    Join Date
    Oct 2007
    Posts
    369
    For your method, all you have to do is check for <0 and, if so, prepend a "-" then convert the absolute value. That works for all cases except the minimum of negative numbers. Because of twos-complement: -INT_MIN == INT_MIN.

  8. #8
    Join Date
    Sep 2009
    Posts
    3
    Yeah I kind of thought of that directly after I posted haha ^_^. Except for I did end up learning about twos complement. I'm glad I joined this forum. I had no idea the amount of things I didn't even know existed.

  9. #9
    Join Date
    Dec 2007
    Posts
    401
    > If you start right and then go left along a number the zeroes have to stay in place as placeholders

    the placeholders can be avoided. just start at the rightmost digit and then go left along a number. finally reverse the resultant string.
    Code:
    #include <string>
    #include <algorithm>
    
    std::string int_to_string( int n )
    {
        if( n == 0 ) return "0" ;
    
        std::string str ;
        bool negetive = n < 0 ;
        if( negetive ) n = -n ;
        if( n < 0 ) return "std::numeric_limits<int>::min()" ;
    
        while( n > 0 )
        {
            str += char( '0' + n&#37;10 ) ;
            n /= 10 ;
        }
    
        if( negetive ) str += '-' ;
        std::reverse( str.begin(), str.end() ) ;
        return str ;
    }
    also, have a look at: http://www.gotw.ca/publications/mill19.htm
    Last edited by vijayan; 09-21-2009 at 01:49 AM.

Similar Threads

  1. Replies: 1
    Last Post: 04-10-2009, 02:16 AM
  2. Replies: 4
    Last Post: 02-05-2009, 10:09 AM
  3. please help me
    By idea2 in forum .NET
    Replies: 7
    Last Post: 02-22-2007, 07:40 PM
  4. Getting a GUI to run
    By Eric in forum Java
    Replies: 4
    Last Post: 04-14-2006, 09:09 AM
  5. Getting a GUI to function
    By Eric in forum Java
    Replies: 1
    Last Post: 11-27-2001, 06:53 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center