Here is one way to do it (although most likely not feasible in your case):
Rewrite function regex_search
as a macro (consider this as an example).
A switch
statement in C and C++ can only take constant values as cases.
Frage
I would like to use switch case
to determine my value with regex
, but it seems that I can't do this way. I can use regex
successfully with if else
, like below:
if (regex_search(dic_char, lowercase)) {
cout << dic_char << endl;
} else if (regex_search(dic_char, uppercase)) {
// do something
} else {
cout << "Not characters." << endl;
}
but I want to do in this way:
switch (dic_char) {
case regex_search(dic_char, lowercase):
cout << dic_char << endl;
break;
case regex_search(dic_char, uppercase):
// do something
break;
default:
cout << "Not characters." << endl;
break;
}
Does anyone know how I do in this way ? Thanks in advance.
Lösung
Here is one way to do it (although most likely not feasible in your case):
Rewrite function regex_search
as a macro (consider this as an example).
A switch
statement in C and C++ can only take constant values as cases.
Andere Tipps
You'll have to do your calculation outside the switch statement and use the resulting value to switch on.
In your particular case, it doesn't make much sense, since there are only two choices anyway.
But a more general pattern would be:
result = do_calculation(p1,p2,..)
switch(result) {
case 1: ...
....
}
The if-else
version and the switch-case
version you provided are logically different. In the former the condition is on the return value of regex_search()
method while in later form the condition is on the value of dic_char'. To write
switch-case` version equivalent to the former you can you following :
int res = regex_search(param); ///this method must return int/convertible to int value
switch(res)
{
case ...
}
You can create an enum
containing the valid return values from the method and use it in case statement.