Reputation:
I'm currently learning C++ but am having trouble wrapping my head around recursion. The problem at hand is to go through a string and only return the operators within it: i.e., '(' or '[' or '{' or ')' or '}' or ']'. Unfortunately, my program keeps returning the empty string. Any help would be appreciated.
#include <string>
string operatorsOnly(string s) {
if (s.length() == 0) {
return "";
}
if (s[0] != '(' or '[' or '{' or ')' or '}' or ']') {
return operatorsOnly(s.substr(1, s.length() - 1));
}
else {
return s[0] + operatorsOnly(s.substr(1, s.length() - 1));
}
}
Upvotes: 0
Views: 236
Reputation: 60308
You can't compare a variable against multiple values with that syntax. You need to do:
if (s[0] != '(' or s[0] != '[' or s[0] != '{' or s[0] != ')' or s[0] != '}' or s[0] != ']') {
// ...
Upvotes: 1