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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With