我一直在想一种将字符串转换为整数的方法,我知道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;
}
对于像您这样的简单情况,伪代码解决方案可以是:
//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之后,函数中的whitespacepos应该已经发生了更改。
输入的样本运行=+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
请注意,我还没有测试过它。此外,这可以以更好的方式在循环中实现(而不是递归)
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;