|
-
February 17th, 2004, 06:23 AM
#1
easy if / else question...
Hi
I've got comparable code:
Code:
if (strstr(string, "Statement1")
function1;
if (strstr(string, "Statement2")
function2;
if (strstr(string, "Statement3")
function3;
if (strstr(string, "Statement4")
function4;
Problem: I need a default case... I could solve it with a flag like this:
Code:
if (strstr(string, "Statement1")
{
function1;
flag=TRUE;
}
if (strstr(string, "Statement2")
{
function2;
flag=TRUE;
}
....
if(!flag)
{
fuction_default;
}
or maybe like this
Code:
if (strstr(string, "Statement1")
{
function1;
}
else
{
if (strstr(string, "Statement2")
{
function2;
}
else
{
if (strstr(string, "Statement3")
{
function3;
}
else
{
if (strstr(string, "Statement4")
{
function4;
}
else
{
fuction_default;
}
}
}
}
??
I dont think its the best way... I suppose that a "switch - case statement" is unfortunately not possible because I need to search the string for many different char-strings...
How would you solve this problem?
thx in advance
-
February 17th, 2004, 06:54 AM
#2
I'd put the search in a void return function
Code:
void evaluate( const string & str )
{
if (strstr(string, "Statement1")
{
function1;
return;
}
if (strstr(string, "Statement2")
{
function2;
return;
}
...
...
fuction_default();
}
It might be more OO to use a class though.
Derive all the functions from an abstract base function interface.
Have a container class that holds base function pointers with associated strings eg. statement1 with function1.
The container class can then have methods like add_function(statement1,function1) and add_default(function_default).
Finally a call to the conatiner class with a string will evaluate the correct function.
The controller can be responsible for destroying the functions.
"strstr" can be implemented within the controller.
The benefit of this is that new function/string pairs can be added easily and dynamically.
Also the complexity is wrapped up for client code eg.
Code:
// At start-up
Controller C;
C.add_function("Statement1",new Function1());
C.add_function("Statement2",new Function2());
C.add_function("Statement3",new Function3());
...
...
C.add_default(new DefaultFunction1());
// When the call is needed
C.evaluate( RuntimeString );
Cheers,
ljhw
-
February 17th, 2004, 06:56 AM
#3
I would do:
Code:
if (strstr(str, "item1"))
; // do something
else if (strstr(str, "item2"))
; // do something
else if (strstr(str, "item3"))
; // do something
else if (strstr(str, "item3"))
; // do something
else if (strstr(str, "item4"))
; // do something
else if (strstr(str, "item5"))
; // do something
else {
// catch all other casees here
}
-
February 17th, 2004, 07:31 AM
#4
thanks!
Thank you both for your answers... I did it exactly like j0nas said and it works fine!!
Greetz
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|