[英]Converting string to long
I'm trying to convert a string to long. 我正在尝试将字符串转换为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*
; atol()
需要一个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()
: 没有从std::string
到const char*
的隐式转换,所以如果你真的想使用atol()
,你必须调用std::string::c_str()
方法来获得原始的类C字符串指针传递给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()
: 更好的C ++方法是使用stol()
(自C ++ 11以来可用),而不依赖于像atol()
这样的C函数:
long myLong = std::stol(myString);
atol
gets as parameter a const char*
(C-style string), but you are passing as parameter a std::string
. atol
获取const char*
(C样式字符串)作为参数,但是您将作为参数传递给std::string
。 The compiler is not able to find any viable conversion between const char*
and std::string
, so it gives you the error. 编译器无法在const char*
和std::string
之间找到任何可行的转换,因此它会给出错误。 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
. 您可以使用string
成员函数std::string::c_str()
,它返回一个c样式的字符串,相当于std::string
的内容。 Usage: 用法:
string str = "314159265";
cout << "C-ctyle string: " << str.c_str() << endl;
cout << "Converted to long: " << atol(str.c_str()) << endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.