Not yet having learned something does not make you dumb, hopefully it just makes yo eager to learn.
Personally I think what the book shows is not a very good example, I would have preferred the example to be:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include "std_lib_facilities.h"
int main()
{
cout << "please enter two names\n";
string first;
string second;
cin >> first >> second;
if (first == second) // for every test that is related, you should have only one "if(condition)" statement
{
cout << "that's the same name twice\n";
}
else if (first < second) // if can be followed by several "else if(condition)" statements
{
cout << first << "is alphabetically before" << second << '\n';
}
else // but for every if, you can have only one "else" statement without a condition. This one will be executed if none of the above conditions were appicable
{
cout << first << " is alphabetically after " << second <<'\n';
}
}
|
and this is why:
1. if you use an if statement without brackets, only the next command depends on the condition, it often happens that you want to do multiple things if a condition is true (for example store a value and print it). If you use brackets, everything within the brackets depends on the condition, so if you get used to this you will not get confused if you want to do multiple things.
2. you can also tell the program what to do if a condition is not true using the else statement, because a condition is always true or not true, this means that you will always get some output.
The condition, in the code, to print something is that first_name < second_name and second_name < third name.
If, for example, first_name > second_name, it won't display anything. |
This is because like xSoloDrop stated, there are more outcomes than the ones you were testing for. If you had used an else statement, you would also have gotten an output if condition that you provided was not listed.
So to overcome your problem, make sure that your program knows what to do in every possible condition, either by listing all conditions, or by using the else statement (or both using the "else if").
Note that the number of possibilities will grow fast, with 2 names there were 3 options, with 3 names there are 9, with 4 names there will be 16 options, with x names there will be 2^(x) possibilities (also including the options where variables can be equal).
To list them all becomes unattractive very fast. Later you will probably learn about using functions, that will make solving this problem possible for large numbers of names too.
Kind regards, Nico