The strequal function is supposed to return true if and only if its two C string arguments have exactly same text. Explain what the problems with the implementation of the function are, and show a way to fix them.
// return true if two C strings are equal
bool strequal(const char str1[], const char str2[])
{
while (str1 != 0 && str2 != 0) // zero bytes at ends
{
if (str1 != str2) // compare corresponding characters
return false;
str1++; // advance to the next character
str2++;
}
return str1 == str2; // both ended at same time?
}
int main()
{
char a[15] = "Wang, A.";
char b[15] = "Wang, R.";
if (strequal(a,b))
cout << "They're the same person!\n";
}
#include <iostream>
using namespace std;
// return true if two C strings are equal
bool strequal(char str1[], char str2[])
{
char *st1 = str1, *st2 = str2;
while (*st1 != 0 && *st2 != 0) // zero bytes at ends
{
if (*st1 != *st2) // compare corresponding characters
return false;
st1++; // advance to the next character
st2++;
}
return true; // both ended at same time?
}
int main()
{
char a[15] = "Wang, R.";
char b[15] = "Wang, R.";
if (strequal(a, b))
cout << "They're the same person!\n";
else
cout << "They're not the same person\n";
}
Comments
Leave a comment