I was helping someone with some homework when I came upon something strange. I don't use C++, but I figured the function find() would work like any other language. However, in the first example below, an email with the name ericsomthing@gmail.com does not evaluate true when looking for a space using find(' ').
if (classRosterArray[i]->GetEmailAddress().find(' ') >= 0) // evaluated true even though i dont know why
In the second example, find(' ') works but only when stored in a local variable.
int test = classRosterArray[i]->GetEmailAddress().find(' ');
if (test >= 0) // evaluates false as expected
More verbose example of the code is shown below
Strange broken code:
void Tester::printInvalidEmails() {
NUM_STUDENTS = LAST_INDEX + 1;
for (int i = 0; i < NUM_STUDENTS; ++i) {
int test = classRosterArray[i]->GetEmailAddress().find(' ');
int test1 = classRosterArray[i]->GetEmailAddress().find('@');
int test2 = classRosterArray[i]->GetEmailAddress().find('.');
if (classRosterArray[i]->GetEmailAddress().find(' ') >= 0) {
cout << classRosterArray[i]->GetEmailAddress() << endl;
}
if (classRosterArray[i]->GetEmailAddress().find('@') == -1) {
cout << classRosterArray[i]->GetEmailAddress() << endl;
}
if (classRosterArray[i]->GetEmailAddress().find('.') == -1 ) {
cout << classRosterArray[i]->GetEmailAddress() << endl;
}
}
}
But this code works:
void Tester::printInvalidEmails() {
NUM_STUDENTS = LAST_INDEX + 1;
for (int i = 0; i < NUM_STUDENTS; ++i) {
int test = classRosterArray[i]->GetEmailAddress().find(' ');
int test1 = classRosterArray[i]->GetEmailAddress().find('@');
int test2 = classRosterArray[i]->GetEmailAddress().find('.');
if (test >= 0) {
cout << classRosterArray[i]->GetEmailAddress() << endl;
}
if (test1 == -1) {
cout << classRosterArray[i]->GetEmailAddress() << endl;
}
if (test2 == -1 ) {
cout << classRosterArray[i]->GetEmailAddress() << endl;
}
}
}
Why does storing the value of find as a local variable 'test' fix the problem?
Aucun commentaire:
Enregistrer un commentaire