Overall, something is either true or false:
1 2 3 4
|
if ( condA )
// condA was true
else
// condA was false
|
When you have independent if-clauses:
1 2 3 4 5
|
if ( condA )
// condA was true
if ( condB )
// condB was true
|
the second if-statement does not care about the first if-statement.
Program has to test both conditions.
The 'products' IS-A std::string and strings cannot be "foo" and "bar" simultaneously. They can be either "foo" or "bar" or something else.
One could have:
1 2 3 4 5 6 7
|
if ( products == "foo" ) {
products = "bar";
}
if ( products == "bar" ) {
// something
}
|
in which the body of the first if-statement affects the condition of the following if-statement. They are no longer entirely independent. You don't have that.
Since you do know that 'products' cannot be simultaneously "foo" and "bar", you can optimize and use the
if .. else
:
1 2 3 4 5 6
|
if ( products == "foo" ) {
// something
}
else if ( products == "bar" ) {
// another
}
|
Now the second test is skipped, if products is "foo".
Lazy evaluation.
Why do you have both
string candies;
and
std::string junkfoods;
?
at most one of them will get "value" due to your conditions.
For that, a single variable would be enough:
1 2 3 4 5 6 7 8 9 10 11 12
|
string purchase;
cout<<endl;
if (products == "Candies")
{
cout<<"Candies: \nSnow Bear = Php 1.00\nJudge = Php 1.00"<<endl<<endl;
}
else if (products == "Junk Foods")
{
cout<<"Junk Foods: \nClover = Php 7.00\nPiaotos = Php 13.00"<<endl<<endl;
}
cout<<"Enter your choice: ";
cin>>purchase;
|
I presume there is "price" too, but you did not show it's handling in your example.
One more thing:
Pay attention to the semicolon:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
if (products == "Candies");
{
cin>>candies;
}
// means same as
if (products == "Candies")
{}
{
cin>>candies;
}
|
In other words, no matter what the value of products is, the cin>>candies; will always execute. It is not in the if's body.