前缀表示法字符串到int转换

时间:2012-04-06 01:41:38

标签: c++ string int prefix

我一直在想一种将字符串转换为整数的方法,我知道C中的旧atoi()以及将字符串类型转换为整数的sstream函数。我正在尝试编写一个程序,它采用前缀表示法并递归地生成结果。程序工作,当我使用char而不是字符串,但我不确定我是如何使用字符串来解决这个问题。我必须拥有它,以便用户输入+ 3 3,结果为6.

#include <iostream>
#include <string>
using namespace std;

int stringToAscii(string value){
    if (value == '+')
        return '+';
    if (value == '*')
        return '*';
    if (value == '-')
        return '-';
    if (value == '/')
        return '/';
}

int prefixNotationCalc(string value){
    char newValue = value;
    int number1=0;
    int number2=0;
    //while () {
        switch (newValue){
        case '*':
            cin >> number1;
            cin >> number2;
            return (number1*number2);
            break;
        case '+':
            cin >> number1;
            cin >> number2;
            return (number1+number2);
            break;
        case '-':
            cin >> number1;
            cin >> number2;
            return (number1-number2);
            break;
        case '/':
            cin >> number1;
            cin >> number2;
            return (number1/number2);
            break;
        }
    //}
}

int main (){
    //The function takes in a string value
    string value;
    cin >> value;
    cout << "Result is: "<< prefixNotationCalc(value)<< endl;
    return 0;
}

2 个答案:

答案 0 :(得分:1)

对于您的简单情况,伪代码解决方案可以是:

//assuming input like + 3 * 4 - * 6 10 8  
//(note: the ints can have more than one digit)
int prefixNotationCalc(string input, int &start)
{
  string token = scan_from_start_of_string_to_first_whitespace
  int whitespace_pos = whitespace_position
  if (token contains digits)
    return int_equivalent_of_token
  else 
    int op1 = prefixNotationCalc(input, whitespace_pos)
    int op2 = prefixNotationCalc(input, whitespace_pos)
    switch(token as operator)
      case + : return op1 + op2
       //...
}

请注意,在提取op1之后,whitespace_pos应该在函数中发生了变化。

运行输入的样本= + 3 * 4 - * 6 10 8

令牌,op1,op2
+,3,* 4 - * 6 10 8
3
*,4, - * 6 10 8
4
- ,* 6 10,8 *,6,10 6
10个
8

请注意,我还没有测试过。此外,这可以以更好的方式在循环(而不是递归)中实现

答案 1 :(得分:0)

declare a main string and a temp string;
declare an int number variable;
declare an int STL stack;
ask the user for the string and enter it into the main string;
declare an index variable and set its value to (main string length - 1);
start at the end of the string and check if that element is a digit;
     if it is a digit, push that digit into the temporary string, decrease
     the index variable, and check if the next element is also a digit;
     repeat this until you run into an element other than a digit;
     reverse the temp string;
     number = atoi(temp.c_str());
     push number onto the stack;
     repeat;