How do you convert a C++ string to an int? [duplic

2019-01-04 09:05发布

Possible Duplicate:
How to parse a string to an int in C++?

How do you convert a C++ string to an int?

Assume you are expecting the string to have actual numbers in it ("1", "345", "38944", for example).

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.

8条回答
啃猪蹄的小仙女
2楼-- · 2019-01-04 09:35
#include <sstream>

// st is input string
int result;
stringstream(st) >> result;
查看更多
戒情不戒烟
3楼-- · 2019-01-04 09:35
Melony?
4楼-- · 2019-01-04 09:36

Perhaps I am misunderstanding the question, by why exactly would you not want to use atoi? I see no point in reinventing the wheel.

Am I just missing the point here?

查看更多
霸刀☆藐视天下
5楼-- · 2019-01-04 09:40

I have used something like the following in C++ code before:

#include <sstream>
int main()
{
    char* str = "1234";
    std::stringstream s_str( str );
    int i;
    s_str >> i;
}
查看更多
贪生不怕死
6楼-- · 2019-01-04 09:41

C++ FAQ Lite

[39.2] How do I convert a std::string to a number?

https://isocpp.org/wiki/faq/misc-technical-issues#convert-string-to-num

查看更多
狗以群分
7楼-- · 2019-01-04 09:46

Let me add my vote for boost::lexical_cast

#include <boost/lexical_cast.hpp>

int val = boost::lexical_cast<int>(strval) ;

It throws bad_lexical_cast on error.

查看更多
登录 后发表回答