2012-04-22 67 views
1

这里是我到目前为止的代码:如何将字符串转换为C++中的整数?

#include "stdafx.h" 
#include <iostream> 
#include <string> 
using namespace std; 

int main() 
{ 
string exp; 
cout << "Enter a number and raise it to a power" << endl; 
cin >> exp; 
int num = exp[0]; 
int pow = exp[2]; 

cin.get(); 
cin.ignore(256,'\n'); 
} 

基本上,我试图让一个程序,你可以输入类似“2^5”,它会为您解决。到目前为止,我已经取得了字符串的第一个和第三个值,并将它们称为“num”和“pow”。 (数量,功率)如果您尝试类似“cout < <”;“它会给你十进制的Ascii值。我如何将它转换为小数?

回答

1
int num; 
    char op; 
    int pow; 
    if ((std::cin >> num >> op >> pow) && op == '^') { 
      // do anything with num and pow 
    } 
6

您可以从cin直接读取到整数变量:

int n; 
std::cin >> n; 

,但你不能进入自然期待表情的方式。

阅读2^5您可以使用std::stringstream

int pos = exp.find('^'); 
int n; 
std::stringstream ss; 
if(pos != std::npos){ 
    ss << exp.substr(0, pos); 
    ss >> n; 
} 

和第二个变量相似。

该方法在Boost中实现为boost::lexical_cast

更复杂的表达式需要构建解析器,我建议您阅读关于此主题的更多信息。

+0

或使用'的std :: Stoi旅馆()'函数:'N =标准:: Stoi旅馆(exp.substr(0,POS));' – bames53 2012-04-22 19:03:01

0

看来你所有的数字都低于10,在这种情况下exp[0]-'0'exp[1]-'0'就足够了。

2

strtol非常擅长。它读取尽可能多的数字,返回数字,并给你一个指向造成它停止的字符的指针(在你的情况下,这将是'^')。

+0

什么约'atoi'? – Alcott 2012-07-21 07:30:32

+0

@Alcott:'atoi'只给你前两个,没有任何错误报告。 – 2012-07-21 14:54:30