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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:26:30  来源:igfitidea点击:

Convert std::string to integer

c++stringintatoi

提问by Daniel Del Core

I'm trying to convert a std::stringstored in a std::vectorto 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> >::)()constwhich 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]));