0

文字列を整数に変換する方法を考えてみました。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;
}
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 に答える