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.
只需写长myLong = atol(myString.c_str());
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);
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.