如何将 C++ 字符串转换为 int?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/200090/
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
How do you convert a C++ string to an int?
提问by krupan
Possible Duplicate:
How to parse a string to an int in C++?
可能的重复:
如何在 C++ 中将字符串解析为 int?
How do you convert a C++ string to an int?
如何将 C++ 字符串转换为 int?
Assume you are expecting the string to have actual numbers in it ("1", "345", "38944", for example).
假设您希望字符串中包含实际数字(例如,“1”、“345”、“38944”)。
Also, let's assume you don't have boost, and you really want to do it the C++ way, not the crufty old C way.
另外,让我们假设您没有 boost,并且您真的想以 C++ 的方式来做,而不是笨拙的旧 C 方式。
回答by Randy Sugianto 'Yuku'
#include <sstream>
// st is input string
int result;
stringstream(st) >> result;
回答by Martin York
Use the C++ streams.
使用 C++ 流。
std::string plop("123");
std::stringstream str(plop);
int x;
str >> x;
/* Lets not forget to error checking */
if (!str)
{
// The conversion failed.
// Need to do something here.
// Maybe throw an exception
}
PS. This basic principle is how the boost library lexical_cast<>
works.
附注。这个基本原理就是 boost 库的lexical_cast<>
工作原理。
My favorite method is the boost lexical_cast<>
我最喜欢的方法是提升 lexical_cast<>
#include <boost/lexical_cast.hpp>
int x = boost::lexical_cast<int>("123");
It provides a method to convert between a string and number formats and back again. Underneath it uses a string stream so anything that can be marshaled into a stream and then un-marshaled from a stream (Take a look at the >> and << operators).
它提供了一种在字符串和数字格式之间转换并再次转换的方法。在它下面使用一个字符串流,所以任何可以被编组到流中然后从流中解组的东西(看看 >> 和 << 运算符)。
回答by ayaz
I have used something like the following in C++ code before:
我之前在 C++ 代码中使用过类似以下内容:
#include <sstream>
int main()
{
char* str = "1234";
std::stringstream s_str( str );
int i;
s_str >> i;
}
回答by Alessandro Jacopson
C++ FAQ Lite
C++ 常见问题精简版
[39.2] How do I convert a std::string to a number?
[39.2] 如何将 std::string 转换为数字?
https://isocpp.org/wiki/faq/misc-technical-issues#convert-string-to-num
https://isocpp.org/wiki/faq/misc-technical-issues#convert-string-to-num
回答by Ryan Ginstrom
Let me add my vote for boost::lexical_cast
让我为 boost::lexical_cast 添加我的投票
#include <boost/lexical_cast.hpp>
int val = boost::lexical_cast<int>(strval) ;
It throws bad_lexical_cast
on error.
它引发bad_lexical_cast
错误。
回答by user12576
Perhaps I am misunderstanding the question, by why exactly would you notwant to use atoi? I see no point in reinventing the wheel.
也许我误解的问题,由到底为什么你会不希望使用的atoi?我认为重新发明轮子没有意义。
Am I just missing the point here?
我只是在这里错过了重点吗?
回答by user27732
in "stdapi.h"
在“stdapi.h”中
StrToInt
This function tells you the result, and how many characters participated in the conversion.
此函数会告诉您结果以及参与转换的字符数。