c++stringlong-integer

Converting string to long


I'm trying to convert a string to long. It sounds easy, but I still get the same error. I tried:

include <iostream>
include <string>    

using namespace std;

int main()
{
  string myString = "";
  cin >> myString;
  long myLong = atol(myString);
}

But always the error:

.../main.cpp:12: error: cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'long int atol(const char*)'

occured. The reference says following:

long int atol ( const char * str );

Any help?


Solution

  • Try

    long myLong = std::stol( myString );
    

    The function has three parameters

    long stol(const string& str, size_t *idx = 0, int base = 10);
    

    You can use the second parameter that to determine the position in the string where parsing of the number was stoped. For example

    std::string s( "123a" );
    
    size_t n;
    
    std::stol( s, &n );
    
    std::cout << n << std::endl;
    

    The output is

    3
    

    The function can throw exceptions.