/* This program takes two strings on the comand line and compares them to see if they are identical or equal to the string "Fred". The point of this is to show you that when you use the elements of argv as a C-style string, you'll get unexpected results. The takeaway is that you should always convert the strings in argv to C++-style strings. */ #include #include using namespace std; int main(int argc, char **argv) { string a1, a2; /* Error check and print the two words. */ if (argc != 3) { cerr << "usage: bin/argc-beware word1 word2\n"; return 1; } printf("Word 1: %s\n", argv[1]); printf("Word 2: %s\n", argv[2]); /* This automatically converts them to C++ strings. */ a1 = argv[1]; a2 = argv[2]; /* Now do various comparisons with the C and C++ versions */ printf("Comparing them as C-style strings: %d\n", (argv[1] == argv[2])); printf("Comparing them as C++ strings: %d\n", (a1 == a2)); printf("Equal to the C string \"Fred?\"? %d\n", (argv[1] == "Fred")); printf("Equal to the C++ string \"Fred?\"? %d\n", (a1 == "Fred")); printf("Doing the comparison with a typecast: %d\n", ((string) argv[1] == (string) argv[2])); return 0; }