sorting strings

closed account (j1AR92yv)
This is what I have,

string a;
string b;
string c;
cout << "Please enter a string.";
cin >> a;
cout << "Please enter a second string.";
cin >> b;
cout << "Please enter a third string.";
cin >> c;

if ("a" > "b" && "a" > "c")
{
cout << a << " ";
if ("b" > "c")
{
cout << b << " " << c << endl;
}
else
{
cout << c << " " << b << endl;
}
}
else if ("b" > "a" && "b" > "c")
{
cout << b << " ";
if ("a" > "c")
{
cout << a << " " << c << endl;
}
else
{
cout << c << " " << a << endl;
}
}
else if ("c" > "a" && "c" > "b")
{
cout << c << " ";
if ("a" > "b")
{
cout << a << " " << b << endl;
}
else
{
cout << b << " " << a << endl;
}
}

}


I know I can probably make this simpler by using vectors and sort, but I'm not sure how to implement it.
When I put in, a b c, it comes out bac
Last edited on
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
#include <iostream>
#include <string>
#include <algorithm> // for std::swap

int main()
{
    std::string a;
    std::cout << "Please enter a string: ";
    std::cin >> a;

    std::string b;
    std::cout << "Please enter a second string: ";
    std::cin >> b;

    std::string c;
    std::cout << "Please enter a third string: ";
    std::cin >> c;

    using std::swap ; // used to exchange the values of two variables

    if( b < a ) swap(a,b) ;  // a <= b after this
    if( c < a ) swap(a,c) ;  // a <= c after this
    // now, the smallest value is in a

    if( c < b ) swap(b,c) ; // b <= c after this
    // now, the second smallest value is in b

    std::cout << a << '\n' << b << '\n' << c << '\n' ;
}
Topic archived. No new replies allowed.