Hello all,
I'm going through an old C++ textbook to re-familiarize myself after some time away from it, and am just going front to back to and answering all of the questions/doing all of the code in the book to do it.
Anyway, I'm at a point where strings are being compared using ASCII values, and I am either misunderstanding things, or the book answers are incorrect. Trying to figure out which one and why. Here are the questions:
Indicate whether each of the following relational expressions is true or false. Refer to the ASCII table in Appendix B if necessary.
A) "Bill" == "BILL"
B) "Bill" < "BILL"
C) "Bill" < "Bob"
D) "189" > "23"
E) "189" > "Bill"
F) "Mary" < "MaryEllen"
G) "MaryEllen" < "Mary Ellen"
The book says the answers are:
A) False B) False C) False D) True E) False F) False G) False
According to the book, if comparing 2 strings, the first operand is less than the second operand if the first mismatched character in the first operand is less than its counterpart in the second operand.
The book doesn't specifically mention what happens when they are different lengths. I would think that a longer string would be considered greater because its ASCII value would be a longer number than a shorter string by default. Going by that logic:
A) False B) False C) False D) True E) False F) True G) True
When that didn't match up with the answer the book provided, I figured my assumption was wrong and that would mean that it is based on the first mismatched character no matter what, which would lead me to believe the answers should be:
A) False B) False C) True D) False E) False F) True G) False
So I wrote a quick program to see what it would say the answers should be. Here's the code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <iostream>
#include <string>
using namespace std;
int main()
{
string string1, string2;
cout << "This program will compare two strings"
<< "and tell you which one is the greater"
<< "of the two.\n Enter the first string: ";
getline(cin, string1);
cout << "Enter the second string: ";
getline(cin, string2);
if (string1 > string2)
cout << "The first string is the greater string." << endl;
else if (string1 == string2)
cout << "The strings are equal." << endl;
else
cout << "The second string is the greater string." << endl;
return 0;
}
|
When I enter the values into that, I come up with the following answers:
A) False B) False C) True D) False E) False F) True G) False
So am I completely misunderstanding this? I find it odd that no matter how I look at it, I don't match up with the book answers, which leads me to believe that the book is wrong. Either that or I'm completely overlooking something.
Thanks in advance for any input!