我一直在尝试计算二次方程的判别式。不过,我决定使用正则表达式,这样用户就可以输入整个方程,而不是重复多次的信息。该代码运行良好,直到我尝试使用用户的输入,我得到:
terminate called after throwing an instance of 'std::invalid_argument'
what(): stoi
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int match(string str, regex rgx){
smatch m;
regex_search(str, m, rgx);
return stoi(m[1]);
}
int main(){
string eq = "3x^2 + 5x + 9 = 0" // sample test
//cout << "Paste a quadratic equation here: ", cin >> eq;
regex ar(R"~(\d(?=(x\^2)|x\*\*2))~");
regex br(R"~(\d(?=x)(?!(x\^2)|(x\*\*2)))~");
regex cr(R"~(\d(?=\s?\=))~");
double r = match(eq,br)*match(eq,br) - 4*match(eq,ar)*match(eq,cr);
cout << "The discriminant is: " << r << endl;
return 0;
}
我调试了,似乎正则表达式捕获“3x^2”而不仅仅是“3”。我阅读了文档和类似的问题,但一无所获。那么,我做错了什么?
程序崩溃是因为我们试图访问由不正确的正则表达式提供的不存在的子匹配。为了举例,我稍微纠正了它们。
regex ar(R"~((\d+)x\^2)~");
regex br(R"~((\d+)x[^\^])~");
regex cr(R"~((\d+)\s*=)~");
我建议您阅读更多有关 C++ 中的正则表达式语法的内容。 B. Stroustrup 所著的《C++ 编程语言》一书中有一章介绍了这个主题。