0

我一直在想办法将字符串转换为整数,我知道 C 中的旧 atoi() 以及将字符串类型转换为整数的 sstream 函数。我正在尝试编写一个程序,该程序采用前缀表示法并递归地产生结果。当我使用 char 而不是 string 时,该程序可以工作,但我不确定我应该如何使用字符串来解决这个问题。我必须拥有它,以便用户输入 + 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;
}
4

2 回答 2

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

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

于 2012-04-06T07:15:03.290 回答
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;
于 2014-12-11T17:24:15.833 回答