7

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?

0

4 Answers 4

15

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.

Sign up to request clarification or add additional context in comments.

Comments

8

Just write

long myLong = atol(myString.c_str());

1 Comment

is this c 11 standard?
4

atol() requires a const char*; there's no implicit conversion from std::string to const char*, so if you really want to use atol(), you must call the std::string::c_str() method to get the raw C-like string pointer to be passed to atol():

// myString is a std::string
long myLong = atol(myString.c_str());

A better C++ approach would be using stol() (available since C++11), without relying on a C function like atol():

long myLong = std::stol(myString);

Comments

1

atol gets as parameter a const char* (C-style string), but you are passing as parameter a std::string. The compiler is not able to find any viable conversion between const char* and std::string, so it gives you the error. You can use the string member function std::string::c_str(), which returns a c-style string, equivalent to the contents of you std::string. Usage:

string str = "314159265";
cout << "C-ctyle string: " << str.c_str() << endl;
cout << "Converted to long: " << atol(str.c_str()) << endl;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.