使用regex来帮助我使用计算器c++
using regex to help me on my calculator c++
我正在做一个c++计算器,我正在使用正则表达式来生成语法。
但我很难验证表达式。
这是我的代码:
#include <regex>
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
int main(){
string blah;
cout << "Expression :n";
cin >> blah;
regex numb("[-+]?[0-9]*\.?[0-9]+");
regex ope("(\+|-|/|\*|\(|\))");
regex exp("[-+]?[0-9]*\.?[0-9]+(\+|-|/|\*|\(|\))");
smatch numbMatch;
smatch opeMatch;
smatch expMatch;
if (!regex_search(blah, expMatch, exp)){
cout << "Invalid expression" << endl;
return main();
}
else{}
do{
if (regex_search(blah, numbMatch, numb)){
for (unsigned int j = 0; j < numbMatch.size(); ++j)
cout << "Number n" << numbMatch[j] << endl;
blah = numbMatch.suffix().str();
}
if (regex_search(blah, opeMatch, ope)){
for (unsigned int i = 1; i < opeMatch.size(); ++i){
cout << "Operator n" << opeMatch[i] << endl;
blah = opeMatch.prefix().str() + opeMatch.suffix().str();
}
}
} while (true); {}
}
如果我把我的表情像a4+4一样,那就没用了。它通过了我的第一个正则表达式,但没有返回到main()
。
首先,递归函数通常是个坏主意。像这样的东西要好得多:
while (!regex_search(blah, expMatch, exp)){
cout << "Invalid expression" << endl;
cout << "Expression :n";
cin >> blah;
}
无论如何,regex_search:
返回目标序列中的某个子序列(主题)匹配正则表达式rgx(模式)
字符串"a4+4"匹配,因为字符串中有表达式"4+4"。尝试使用如下正则表达式查找函数regex_match:
regex exp("[-+]?[0-9]*([-+*/][-+]?[0-9]+)*$");
while (!regex_match(blah, expMatch, exp)){
cout << "Invalid expression" << endl;
cout << "Expression :n";
cin >> blah;
}
do..while循环也是一个无限循环。至少尝试:
} while (!blah.empty());
相关文章:
- 使用 BMI 计算器对C++中的数字进行四舍五入的问题
- 我在c ++矩阵计算器程序中找不到错误
- C++计算器,不能单独除以 0
- 如何正确解析子字符串,以便它们对我的新手计算器有效?
- Arduino 基础 2 计算器无法C++工作
- 需要有关我的平均计算器代码的建议
- C++ - 在我尝试制作一个简单的计算器时有一个"uninitialized local variable y used"警告
- 野牛/flex:计算器将双精度值解释为整数,所以我添加了 YYSTYPE 双精度 #define 但我有多个编译错误
- C++计算器运算符
- 使用WIN32 API的击球平均计算器
- RPN计算器c++错误处理和多个运算符
- C++查找用于构建单行计算器
- 如何修复这个基本计算器
- 用于加法和减法的十六进制计算器
- 桌面计算器出现问题.C++程序设计语言
- 如何对堆栈中的所有项目求和?Postfix计算器
- RPN计算器使用头文件进行计算操作和堆栈;用于堆栈的矢量
- 如何在我的基本计算器中循环遍历数组
- 如果 GPA 计算器的语句问题
- 我的C++计算器似乎出了什么问题?