如何在 C++ 中计算字符串的算术运算
how to evaluate arithmetic operation from string in c++
我正在努力解决C ++中与字符串相关的问题。
假设我有一个字符串 s="6*6+4*8+6/6/6-632+81";
我的主要目标是从字符串进行算术运算。 因此,在下面的代码中,当整数值为 1 位整数时,我得到了正确的结果。
字符串数学[]="1+2"; 结果:3;
但是当字符串数学[]="10+20"那么 结果为:2;
#include<iostream>
#include<string>
using namespace std;
int main()
{
int A,B,val;
char math[]="1+2";
//char math[]="10+20";
for (int i = 0 ; math[i]!=NULL; i++)
{
char ch =math[i];
if(ch == '+' || ch == '-' || ch == '*' || ch == '/')
{
char ch2=math[i-1];
A=(ch2-'0');
char ch3=math[i+1];
B=(ch3-'0');
switch (ch) /* ch is an operator */
{
case '*':
val = A * B;
break;
case '/':
val = A / B;
break;
case '+':
val = A + B;
break;
case '-':
val = A - B;
break;
}
}
if ( math[i] == NULL)
{
break;
}
}
cout<<val<<endl;
}
所以我意识到问题是选择 A 和 B 的值.这里我没有选择整个数字。 所以我希望我的 A 是 10 和 B 20.但我的程序选择 A=0 和 B=2.所以为了得到整个数字 .like A=10,我在代码中进行了这些更改[仅用于 A.As 测试]。
if(ch == '+' || ch == '-' || ch == '*' || ch == '/')
{
char total;
int k=i-1;
cout<<"k="<<k<<endl;
char p;
p=math[k];
for(;k>-1 && isdigit(p)==true;k--)
{
char c=math[k];
cout<<"c"<<c<<endl;
total=math[i-1];
total=total+c;
}
char ch2=total;
// char ch2=math[i-1];
cout<<"ch2:"<<total<<endl;
A=(ch2-'0');
cout<<"A="<<A<<endl;
但是现在对于 A 来说,我得到了垃圾价值。现在我该如何解决这个问题。更具体地说,获取 A=10 和 B=20 的值,并得到此数学表达式的正确结果。
使用 std::string 和 std::stringstream like
#include <iostream>
#include <sstream>
#include <string>
using std::cout;
using std::string;
using std::stringstream;
void func(double &result, char op, double num);
int main() {
string math = "6*6+4*8+6/6/6-632+81";
stringstream mathStrm(math);
double result;
mathStrm >> result;
char op;
double num;
while (mathStrm >> op >> num) {
cout << "op: " << op << ", num: " << num << 'n';
func(result, op, num);
}
cout << result << 'n';
}
void func(double &result, char op, double num) {
switch (op) {
case '+':
result += num;
break;
case '-':
result -= num;
break;
case '*':
result *= num;
break;
case '/':
result /= num;
}
}
请注意,字符串是从左到右计算的,没有优先级。
相关文章:
- 算术运算的结果类似于:C浮点变量中的1/3
- 更快的C++算术运算
- 为什么循环体中的一个基本算术运算执行得比两个算术运算慢
- 为什么对无符号字符进行算术运算会将它们提升为有符号整数
- 如何在 C++ 中计算字符串的算术运算
- 复数的算术运算
- 具有非常非常大数字的算术运算
- 如何使用C++中的处理器指令来实现快速算术运算
- boost::spirit::x3 phrase_parse 在进入 Vector 之前进行算术运算
- C++中混合数据类型的算术运算
- C++:编译器是否优化整数 + 浮点算术运算?
- 如何在特征中对二维数组的列执行简单的算术运算
- 使用数字列表和算术运算获取目标数字
- C++:“enable_if”用于限制支持特定算术运算的类型
- 如何正确避免 SIGFPE 和算术运算溢出
- 编译器用于编译 128 位整数的基本算术运算的技巧
- 将临时值存储为某种数据类型时,算术运算的标准规则是什么
- 相同的算术运算在 C++ 和 Python 中给出不同的结果
- 带有空的算术运算
- 算术运算和编译器优化