C++ 将 std::string 转换为整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12628428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert std::string to integer
提问by Daniel Del Core
I'm trying to convert a std::string
stored in a std::vector
to an integer and pass it to a function as a parameter.
我正在尝试将std::string
存储在 a 中的 astd::vector
转换为整数并将其作为参数传递给函数。
This is a simplified version of my code:
这是我的代码的简化版本:
vector <string> record;
functiontest(atoi(record[i].c_str));
My error is as follows:
我的错误如下:
error: argument of type ‘const char* (std::basic_string<char, std::char_traits<char>, std::allocator<char> >::)()const' does not match ‘const char*'
How can I do this?
我怎样才能做到这一点?
回答by Pete Becker
With C++11:
使用 C++11:
int value = std::stoi(record[i]);
回答by Indy9000
Use stringstream from standard library. It's cleaner and it's rather C++ than C.
使用标准库中的 stringstream。它更干净,更像是 C++ 而不是 C。
int i3;
std::stringstream(record[i]) >> i3;
回答by Luchian Grigore
record[i].c_str
is not the same as
不一样
record[i].c_str()
You can actually get this from the error message: the function expects a const char*
, but you're providing an argument of type const char* (std::basic_string<char, std::char_traits<char>, std::allocator<char> >::)()const
which is a pointer to a member function of the class std::basic_string<char, std::char_traits<char>, std::allocator<char> >
that returns a const char*
and takes no arguments.
您实际上可以从错误消息中得到这一点:该函数需要 a const char*
,但是您提供了一个类型的参数,该参数const char* (std::basic_string<char, std::char_traits<char>, std::allocator<char> >::)()const
是指向std::basic_string<char, std::char_traits<char>, std::allocator<char> >
返回 aconst char*
并且不带任何参数的类的成员函数的指针。
回答by Darko Veberic
#include <boost/lexical_cast.hpp>
functiontest(boost::lexical_cast<int>(record[i]));