Search code examples
c++visual-c++atoi

Simple example of the "atoi" function in c++


Can someone please give a very simple example on how to use the atoi function? I know how it is supposed to work, but most of the examples are in objective C... Which I have trouble reading with since I haven't really learned it yet . Thanks, in advance!


Solution

  • #include <cstdlib>        // wraps stdlib.h in std, fixes any non-Standard content
    
    std::string t1("234");
    int i1 = std::atoi(t1.c_str());
    int i1b = std::stoi(t1);  // alternative, but throws on failure
    
    const char t2[] = "123";
    int i2 = std::atoi(t2);
    
    const char* t3 = "-93.2"; // parsing stops after +/- and digits
    int i3 = std::atoi(t3);   // i3 == -93
    
    const char* t4 = "-9E2";  // "E" notation only supported in floats
    int i4 = std::atoi(t4);   // i4 == -9
    
    const char* t5 = "-9 2";  // parsing stops after +/- and digits
    int i5 = std::atoi(t5);   // i5 == -9
    
    const char* t6 = "ABC";   // can't convert any part of text
    int i6 = std::atoi(t6);   // i6 == 0 (whenever conversion fails completely)
    
    const char* t7 = "9823745982374987239457823987";   // too big for int
    int i7 = std::atoi(t7);   // i7 is undefined
    

    Because behaviour in this last case is undefined (probably so some implementations can loop adding the next digit to ten times the previous value without spending time checking for signed integer overflow), it's recommended to use std::stoi or std::strtol instead.

    See also: cppreference atoi for documentation including examples; stoi