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

Thread: Convert string to int, int to string

  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

    Re: Convert string to int, int to string

    Ciao, Andreas

    "Software is like sex, it's better when it's free." - Linus Torvalds


    Article(s): Allocators (STL) Function Objects (STL)

  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*'...
    Ciao, Andreas

    "Software is like sex, it's better when it's free." - Linus Torvalds


    Article(s): Allocators (STL) Function Objects (STL)

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

    Re: Convert string to int, int to string

    Winsock must be different from regular Berkeley socket functions.
    Code:
    // sys/socket.h:
    
    ssize_t send(int, const void *, size_t, int);
    By the way, have a look at this link:

    http://www.opengroup.org/onlinepubs/.../socket.h.html

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

    Re: Convert string to int, int to string

    I have had a search and on SUN's online docs they use const char* as the 2nd parameter and int as the 3rd (buffer size) but most of them use const void * and size_t

    The first int parameter is the socket file descriptor
    The last int parameter is a flags parameter

  13. #13
    Join Date
    Oct 2001
    Location
    Dublin, Eire
    Posts
    880

    Re: Convert string to int, int to string

    Whatever it takes ...

    "const char*" is still basically a buffer of bytes, so you should still be able to send your integers as a buffer instead of having to convert them as strings.
    Elrond
    A chess genius is a human being who focuses vast, little-understood mental gifts and labors on an ultimately trivial human enterprise.
    -- George Steiner

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

    Re: Convert string to int, int to string

    You have to cast it though. And casts are better avoided.

    Plus if you are doing binary conversion it is better to use an unsigned char buffer anyway.

Posting Permissions

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


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center