c ++ find() 在存储为变量时返回不同的值

Gok*_*oku 1 c++ string if-statement

当我遇到一些奇怪的事情时,我正在帮助某人做一些家庭作业。我不使用 C++,但我认为函数 find() 可以像任何其他语言一样工作。但是,在下面的第一个示例中,使用 find(' ') 查找空格时,名为 ericsomthing@gmail.com 的电子邮件不会评估为 false。

if (classRosterArray[i]->GetEmailAddress().find(' ') >= 0) // evaluated true even though i dont know why
Run Code Online (Sandbox Code Playgroud)

在第二个示例中, find(' ') 有效,但仅当存储在局部变量中时。

int test = classRosterArray[i]->GetEmailAddress().find(' ');
if (test >= 0) // evaluates false as expected
Run Code Online (Sandbox Code Playgroud)

更详细的代码示例如下所示

奇怪的损坏代码:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但这段代码有效:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么将 find 的值存储为局部变量 'test' 可以解决问题?

sco*_*001 6

.find(' ') >= 0 是一个不好的比较。

我猜你希望 find-1如果找不到你要找的东西会返回?当您将结果转换为 an int(您将其分配给int变量时隐式执行的操作)时,它将是-1. 但是 find 的返回类型实际上是无符号的,所以如果你只看返回的原始值,它永远不会< 0(换句话说.find(' ') >= 0永远是真的)。

如果要检查字符串是否确实有空格,请使用:

classRosterArray[i]->GetEmailAddress().find(' ') != std::string::npos
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看文档。具体来说,从页面上npos

static const size_type npos = -1;

尽管定义使用了 -1,但size_type它是无符号整数类型,由于有符号到无符号的隐式转换,npos 的值是它可以容纳的最大正值。这是指定任何无符号类型的最大值的可移植方式。