0

working on a c++ project, I need to iterate on a string ( or char* depending the solution you could provide me ! ). So basically I'm doing this :

void Pile::evalExpress(char* expchar){
    string express = expchar
    regex number {"[+-*/]"};

    for(string::iterator it = express.begin(); it!=express.end(); ++it){
        if(regex_match(*it,number)){
            cout<<*it<<endl;
        }
    }
}

char expchar[]="234*+";
Pile calcTest;
calcTest.evalExpress(expchar);

the iterator works well ( I can put a cout<<*it<<'endl above the if statement and I get a correct output )

and then when I try to compile :

error: no matching function for call to 'regex_match(char&, std::__cxx11::regex&)'
    if(regex_match(*it,number)){
                             ^

I have no idea why this is happening, I tried to don't use iterator and iterate directly on the expchar[i] but I have the same error with regex_match()...

Regards

Vincent

Gozu09
  • 43
  • 2
  • 5

1 Answers1

2

Read the error message! It tells you that you're trying to pass a single char to regex_match, which is not possible because it requires a string (or other sequence of characters) not a single character.

You could do if (std::regex_match(it, it+1, number)) instead. That says to search the sequence of characters from it to it+1 (i.e. a sequence of length one).

You can also avoid creating a string and iterate over the char* directly

void Pile::evalExpress(const char* expchar) {
    std::regex number {"[+-*/]"};

    for (const char* p = expchar; *p != '\0'; ++p) {
        if (regex_match(p, p+1, number)) {
            cout<<*p<<endl;
        }
    }
}
Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521
  • Hello, thanks for your answer. I was a bit confused by the & in the 'char&'... I though that even if there is one character it's still a char* but apprently not. – Gozu09 May 25 '17 at 16:59
  • That means it's a reference to a `char`. Get a [good book on C++](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Jonathan Wakely May 26 '17 at 12:11