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

Thread: char to int?

  1. #1
    Join Date
    Feb 2004
    Posts
    41

    char to int?

    what function copie char to int? i tried memcpy but it deosn work....
    the char is the command line argument....
    thx

  2. #2
    Join Date
    Jun 2001
    Location
    Switzerland
    Posts
    4,443
    Code:
    #include <sstream>
    //...
        const char *c = "123";
        int i;
        //...
        {
            std::stringstram s;
            s<<c;
            if((s>>i).fail()){
                //error
            }
        }
        //use i...
    Gabriel, CodeGuru moderator

    Forever trusting who we are
    And nothing else matters
    - Metallica

    Learn about the advantages of std::vector.

  3. #3
    Join Date
    Oct 2000
    Location
    London, England
    Posts
    4,773
    close to how I do it:

    Code:
    const char * nums( "123");
    
    std::stringstream ss( std::string( nums ) ); // simpler way
    int i;
    std::string garbage;
    ss >> i >> garbage;
    if ( !garbage.empty() ) 
    {
      // error
    }
    return i;
    You can also use boost::lexical_cast which does pretty much that above, and throws a bad_cast exception, though personally I prefer to throw my own exception with a description of what you were trying to cast to what.

  4. #4
    Join Date
    Feb 2004
    Location
    USA - Florida
    Posts
    729
    Another option to keep in mind is using the C-function atoi() which accepts a char*.
    Code:
    #include <iostream>
    #include <cstdlib>
    
    using namespace std;
    
    int main(int argc, char * argv[])
    {   int n = atoi(argv[1]);
        cout << n << endl;
    }
    Hungarian notation, reinterpreted? http://www.joelonsoftware.com/articles/Wrong.html

  5. #5
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652
    Ciao, Andreas

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


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

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