I am studying Starting Out C++ 6th Edition by Tony Gaddis.
I on chapter 4, problem 8 (Sorted Names). The problem is that the author does not go into detail on how to alphabetize 3 random names. He does use 2 names (and #include <cstring>, strcmp) in an example but that doesn't help. I searched other forums but they use code that im not familiar with yet.
Might be too much to ask. I'm about to give up on this $110 book.
I have to input 3 random names. Then those names need to be displayed in alphabetical order.
Here is the exact problem:
8. Sorted Names
Write a program that asks the user to enter three names, and then displays the names sorted in alphabetical order. Assume that none of the names are the same. For example, if the user entered "Charlie," "Leslie," and "Andy," the program would display:
I really don't want to start on another book or subscribe to some solutions site. Any help would be appreciated.
const std::size_t MAX_SZ = 128 ;
char a[MAX_SZ] = "", b[MAX_SZ] = "", c[MAX_SZ] = "" ;
// read in the three names
std::cin.getline( a, MAX_SZ ) ;
std::cin.getline( b, MAX_SZ ) ;
std::cin.getline( c, MAX_SZ ) ;
// compare the names using std::strcmp()
// note: std::strcmp() returns a value less than zero if the first string
// compares lexicographically less than the second.
constbool a_less_than_b = std::strcmp(a,b) < 0 ;
constbool a_less_than_c = std::strcmp(a,c) < 0 ;
constbool b_less_than_c = std::strcmp(b,c) < 0 ;
if( a_less_than_b && a_less_than_c ) // a is the smallest
std::cout << a << '\n' ; // print a
if( b_less_than_c ) std::cout << b << '\n' << c << '\n' ;
else std::cout << c << '\n' << b << '\n' ;
elseif( b_less_than_c ) // b is the smallest
// 1. print b
// 2. if a is less than c then ....
// else ...
else // c is the smallest
@JLBorges-Thanks. I will study your code. Everything that you coded is in my book but no example was ever given to compare 3 names. Just 2 names, which (to me) looks very different than your solution. If I compared 3 names with the book example, I would have to use the "if/else" for every combination possible with 3 names.