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

大憨熊 提交于 2019-12-17 03:31:41

问题


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.


回答1:


#include <sstream>

// st is input string
int result;
stringstream(st) >> result;



回答2:


Use the C++ streams.

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.

My favorite method is the boost 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).




回答3:


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;
}



回答4:


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




回答5:


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.




回答6:


Use atoi




回答7:


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?




回答8:


in "stdapi.h"

StrToInt

This function tells you the result, and how many characters participated in the conversion.



来源:https://stackoverflow.com/questions/200090/how-do-you-convert-a-c-string-to-an-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!