Your textbook mentions that relational operators can be used to compare letters and words, thanks to ASCII. This simple program will ask the user to enter two letters and then two words to see if we can really "sort" these entries alphabetically with relational operators.
Prompts:
This is a Letter and Word sorting program
Enter two different letters separated by a space: [assume user inputs: b a]
Enter two different words separated by a space: [assume user inputs: bob alex]
Output:
a goes before b
alex goes before bob
Notes and Hints:
1) Do NOT convert the user's entry to uppercase. Some of the test cases will be comparing lowercase to uppercase letters (the results are interesting!)
2) Don't worry about the possibility of the user entering the same letters/words or entering something else. Keep this program simple.
#include <iostream>
#include <string>
using namespace std;
int main()
{
char c1, c2;
cout << "First char: ";
cin >> c1;
cout << "Second char: ";
cin >> c2;
string s1, s2;
cout << "Enter first string: ";
cin >> s1;
cout << "Enter second string: ";
cin >> s2;
if(c1 < c2) cout << c1 <<" goes before " << c2 << endl;
if(c1 >= c2) cout << c2 <<" goes before " << c1 << endl;
if(s1 < s2) cout << s1 <<" goes before " << s2 << endl;
if(s1 >= s2) cout << s2 <<" goes before " << s1 << endl;
return 0;
}
Comments
Leave a comment