gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 15:10:33 25 4
gpt4 key购买 nike

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

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

在第二个示例中,find('')有效,但仅当存储在局部变量中时才有效。
int test = classRosterArray[i]->GetEmailAddress().find(' ');
if (test >= 0) // evaluates false as expected

下面显示了更详细的代码示例

奇怪的破损代码:
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;
}
}
}

但是这段代码有效:
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;
}
}
}

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

最佳答案

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

我猜您希望find如果找不到您要查找的内容,它将返回-1?当将结果转换为int时(将其分配给int变量时隐式执行的操作),它将为-1。但是find的返回类型实际上是无符号的,因此,如果仅查看返回的原始值,则永远不能是< 0(换句话说,.find(' ') >= 0将始终为true)。

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

classRosterArray[i]->GetEmailAddress().find(' ') != std::string::npos

有关更多信息,请查看 the docs。具体来说,从 npos 上的页面:

static const size_type npos = -1;

Although the definition uses -1, size_type is an unsigned integer type, and the value of npos is the largest positive value it can hold, due to signed-to-unsigned implicit conversion. This is a portable way to specify the largest value of any unsigned type.

关于c++ - 当存储为变量时,c++ find()返回不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62266682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com