1

到目前为止,这是我的代码:

 #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”。(Number, Power) 如果你尝试类似“cout << num;” 它会给你十进制的ASCII值。如何将其转换为小数?

4

4 回答 4

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.

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

于 2012-04-22T18:50:58.150 回答
2

strtol非常擅长这一点。它读取尽可能多的数字,返回数字,并为您提供一个指向导致它停止的字符的指针(在您的情况下是'^')。

于 2012-04-22T18:56:36.520 回答
1
    int num;
    char op;
    int pow;
    if ((std::cin >> num >> op >> pow) && op == '^') {
            // do anything with num and pow
    }
于 2012-04-22T19:05:08.340 回答
0

在这种情况下,您的所有数字似乎都低于 10,exp[0]-'0'并且exp[1]-'0'就足够了。

于 2012-04-22T18:53:03.203 回答