CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 14 of 14

Hybrid View

  1. #1
    Join Date
    Feb 2004
    Location
    Texas, USA
    Posts
    1,206

    Convert string to int, int to string

    Using std::string, and data type int, how do I convert from int to string, and string back to int?

    The reason I ask is because I'm using winsock (which only sends char*), and I need to know the most EFFICIENT way of converting numbers to strings. When this string is received, the client needs to be able to convert the string back to a number value.

    Also I need to be able to take a hex value (0x85746 for example), convert it to string, and then when the client receives this string, convert it to hex, and then convert the hex to number.

    I will create functions if I have to, but it should be a last resort. If there are any supplied functions for this, please help me out by telling me what they are!

    note: sprintf(...) should be a last resort also, because this would be something you put inside of a custom function to get the job done! Also this function will not allow you to convert string back to number!


    I know this can be done with simple ascii work, but the hex I'm afraid will be much different. Also this gets complicated when you're converting multiple digit numbers.

    For examples, please use the following:

    Convert "4999" to int.

    Convert "0xAFFF" to int.

    Convert 0xAFFF to string.

    Convert 4999 to string.

    Thanks!
    Last edited by MrDoomMaster; October 25th, 2004 at 02:54 PM.

  2. #2
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652

  3. #3
    Join Date
    Jun 2001
    Location
    Orlando, FL
    Posts
    232

    Re: Convert string to int, int to string


  4. #4
    Join Date
    Feb 2004
    Location
    Texas, USA
    Posts
    1,206

    Re: Convert string to int, int to string

    Both of you, thanks. That really helps me out. I was sure this issue had been brought up before, but I couldn't really find any reliable references on it.

    I appreciate the links! Great job!

    *hands both of you a sack of cookies*

  5. #5
    Join Date
    Feb 2004
    Location
    Texas, USA
    Posts
    1,206

    Re: Convert string to int, int to string

    UGh, I tried to create a function to convert from string to int, but its just not working!!! I get -987234876 as a result! (Not that exactly, but you get it right?)

    Here is my function:

    Code:
    
    //==================================================================================
    /*
    || This function will take a Hex, Dec, or Oct number in a string and convert it to
    || an actual number. Note that the second parameter determines the format of the
    || number to be put in the buffer.
    || Returns 0 if failed, 1 if successful.
    */
    //template<class T>
    int WinSock_Utils::String2Num(string sString, NumberFormat nfFormat, int& tBuffer)
    {
        stringstream ssBuffer(sString);
    
        switch(nfFormat)
        {
            case HEX:
                ssBuffer >> hex >> tBuffer;
                break;
    
            case DEC:
                ssBuffer >> dec >> tBuffer;
                break;
    
            case OCT:
                ssBuffer >> oct >> tBuffer;
                break;
    
            default: return 0;
        }
    
        //if(ssBuffer.fail())
        //    return 0;
    
        return 1;
    }
    If you're wondering what NumberFormat is, its simply an enum with HEX, DEC, and OCT. This specifies the formatting of the number in the string.

    Can someone help me out?

  6. #6
    Join Date
    Jun 2001
    Location
    Orlando, FL
    Posts
    232

    Re: Convert string to int, int to string

    Perhaps this might give some ideas.

    Code:
    // Conversion Functions
    template<typename T>
    T fromString(const std::string& s,
                        std::ios_base& (*f)(std::ios_base&) = std::dec) {
       std::istringstream is(s);
       T t;
       is >> f << t;
       return t;
    }
    template<typename T>
    std::string toString(const T& t,
                                    std::ios_base& (*f)(std::ios_base&) = std::dec) {
       std::ostringstream s;
       s << f << t;
       return s.str();
    }
    
    
    int main()
    {  
    
       std::string value_f ( " 0xAFFF " );
       int val_e = fromString<int>( value_f, hex );
       cout << "val_e is [" << val_e << "]" << endl;
    
    }
    Last edited by mop; October 27th, 2004 at 08:14 PM.

  7. #7
    Join Date
    Feb 2003
    Posts
    377

    Re: Convert string to int, int to string

    Quote Originally Posted by MrDoomMaster
    UGh, I tried to create a function to convert from string to int, but its just not working!!! I get -987234876 as a result! (Not that exactly, but you get it right?)

    Here is my function:

    <snip>

    If you're wondering what NumberFormat is, its simply an enum with HEX, DEC, and OCT. This specifies the formatting of the number in the string.

    Can someone help me out?
    Where's the rest of the code? As is your code is fine. I modified it a little and put it into this small but complete and compilable example (hint, hint) that works just fine:
    Code:
    #include <iostream>
    #include <string>
    #include <sstream>
    using namespace std;
    
    typedef enum
    {
        HEX,
        DEC,
        OCT
    } NumberFormat;
    bool String2Num(string sString, NumberFormat nfFormat, int& tBuffer)
    {
        stringstream ssBuffer(sString);
    
        switch(nfFormat)
        {
            case HEX:
                ssBuffer >> hex >> tBuffer;
                break;
    
            case DEC:
                ssBuffer >> dec >> tBuffer;
                break;
    
            case OCT:
                ssBuffer >> oct >> tBuffer;
                break;
    
            default: return false;
        }
    
        //if(ssBuffer.fail())
        //    return 0;
    
        return true;
    }
    
    int main()
    {
        string sHex("0x002A");
        string sDec("29");
        string sOct("027");
    
        int data = 0;
        if (String2Num(sHex, HEX, data))
            cout << "Hex (0x002A) = " << data << std::endl;
        if (String2Num(sDec, DEC, data))
            cout << "Dec (29) = " << data << std::endl;
        if (String2Num(sOct, OCT, data))
            cout << "Oct (027) = " << data << std::endl;
    }

  8. #8
    Join Date
    Oct 2000
    Location
    London, England
    Posts
    4,773

    Re: Convert string to int, int to string

    If you want the most efficient way to send numeric data via TCP/IP then send it binary, but there is a standard network byte order, so use htonl() ntohl() etc.

    send() takes binary but you will need a variable to store as you cannot take the address of a temporary thus send( &(htonl( myInt ) ), sizeof(int)); is forbidden.

    Are you sure winsock takes char* ? Does send() not take const void * as its pointer to data parameter?

  9. #9
    Join Date
    Nov 2002
    Location
    Los Angeles, California
    Posts
    3,863

    Re: Convert string to int, int to string

    To echo NMTop40, use a binary stream.
    Wakeup in the morning and kick the day in the teeth!! Or something like that.

    "i don't want to write leak free code or most efficient code, like others traditional (so called expert) coders do."

  10. #10
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652

    Re: Convert string to int, int to string

    Quote Originally Posted by NMTop40
    Are you sure winsock takes char* ? Does send() not take const void * as its pointer to data parameter?
    Neither one...it takes a 'const char*'...

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