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:48

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楼-- · 2019-01-04 09:53

in "stdapi.h"

StrToInt

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

查看更多
登录 后发表回答