Hi, I am learning about using loops to compare arrays. I need help understanding the following example in my book.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// compstr1.cpp -- comparing strings using arrays
#include <iostream>
#include <cstring> // prototype for strcmp()
int main()
{
usingnamespace std;
char word[5] = "?ate";
for (char ch = 'a'; strcmp(word, "mate"); ch++)
{
cout << word << endl;
word[0] = ch;
}
cout << "After loop ends, word is " << word << endl;
return 0;
}
How does the strcmp function work? Also, what does the for loop body do each time.
char word[5] = "?ate" is simply initializing the character array, right?
The key thing to notice is that the function returns either 0 or non-0. Non-0 converts to true and 0 to false.
On first call to strcmp the question is: Are "?ate" and "mate" equal? They are not and therefore the first character in the array is replaced by value of ch.
Run the program. See the output. It helps in this case.
If you don't have a textbook or reference book to look this up in, then there are many good references online that are only a Google search away - including this very site: