C++中的Char to Int?

dys*_*oco 0 c++ int char

可能重复:
如何将单个char转换为int

好吧,我正在做一个基本的程序,它处理一些输入,如:

2 + 2

所以,我需要添加2 + 2.

我做了类似的事情:

string mys "2+2";
fir = mys[0];
sec = mys[2];
Run Code Online (Sandbox Code Playgroud)

但现在我想将"fir"添加到"sec",所以我需要将它们转换为Int.我试过"int(fir)"但没有奏效.

Alo*_*ave 5

有多种方法可以将字符串转换为int.

解决方案1:使用Legacy C功能

int main()
{
    //char hello[5];     
    //hello = "12345";   --->This wont compile

    char hello[] = "12345";

    Printf("My number is: %d", atoi(hello)); 

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

解决方案2:使用lexical_cast(最合适和最简单)

int x = boost::lexical_cast<int>("12345"); 
Run Code Online (Sandbox Code Playgroud)

解决方案3:使用 C++ Streams

std::string hello("123"); 
std::stringstream str(hello); 
int x;  
str >> x;  
if (!str) 
{      
   // The conversion failed.      
} 
Run Code Online (Sandbox Code Playgroud)