c++regexquadratic

regex_search returns an error when using user input


I've been trying to calculate the discriminant of a quadratic equation. Though, I decided to use regex, so the user could put the entire equation instead of the information repeated times. The code worked well until I tried to use an input from the user, I get a:

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;
}

I debugged, and it seems the regex catches "3x^2" instead of just "3". I read the documentation and similar questions but found nothing. So, what am I doing wrong?


Solution

  • The program crashed because we attempted to access an absent submatch provided by an incorrect regex. I corrected them a little for the sake of example.

    regex ar(R"~((\d+)x\^2)~");
    regex br(R"~((\d+)x[^\^])~");
    regex cr(R"~((\d+)\s*=)~");
    

    I suggest you to read more about the regex syntax in C++. The book "The C++ Programming Language" by B. Stroustrup has a chapter on this topic.