Tony Gaddis Book

Mar 28, 2013 at 7:47am
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.
Last edited on Mar 28, 2013 at 7:48am
Mar 28, 2013 at 8:37am
1) Not everyone have a copy of this book and knows what is in ch4 pr8.
2) Not everyone knows what author mean by "alphabetize"
Please, elaborate your problem and post here.
Mar 28, 2013 at 10:21pm
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:
Andy
Charlie
Leslie

I really don't want to start on another book or subscribe to some solutions site. Any help would be appreciated.
Mar 29, 2013 at 3:13am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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.
const bool a_less_than_b = std::strcmp(a,b) < 0 ;
const bool a_less_than_c = std::strcmp(a,c) < 0 ;
const bool 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' ;
}
else if( b_less_than_c ) // b is the smallest
{
    // TODO:
    // 1. print b
    // 2. if a is less than c then ....
    //    else ...
}
else // c is the smallest
{
    // TODO:
    // ...
}

Last edited on Mar 29, 2013 at 4:35am
Mar 29, 2013 at 5:13am
@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.
Last edited on Mar 29, 2013 at 5:16am
Topic archived. No new replies allowed.