在这种情况下比较字符串的工作方式不同,有什么原因吗?

Comparing strings in this instances work differently, any reason?

有人可以帮我解决这个问题吗?绿色框中的代码块工作正常,但红色框中的代码块工作但不是真的。它正在检查电子邮件是否同时具有“@gmail.com”和“@yahoo.com”。我希望它检查两封电子邮件,以便如果它们都只包含一个“@gmail.com”或“@yahoo.com”,它将退出循环。谢谢!

#include <iostream>
using namespace std;

int main()
{
    string emailOne_, emailTwo_;
    bool valid = true;

do
{
    cout << "Email: ";
    cin >> emailOne_;
    cout << "Re-enter email: ";
    cin >> emailTwo_;

    if (emailOne_.compare(emailTwo_) != 0)
    {
        valid = false;
        cerr << "\t[*] ERROR: EMAILS DO NOT MATCH\n\n";
    }
    else
    {
        valid = true;
    }

    string myArray[] = { "@gmail.com", "@yahoo.com" };
    int arrSize = sizeof(myArray) / sizeof(myArray[0]);
    for (int i = 0; i < arrSize; i++)
    {
        auto found = emailOne_.find(myArray[i]);
        if (found == string::npos)
        {
            valid = false;
            cerr << "\t[*] ERROR: EMAILS MUST HAVE @gmail.com or @yahoo.com\n\n";
            break;
        }
        else
        {
            valid = true;
        }
    }
} while (valid == false);

return 0;
}

您的代码有一些问题

  • auto found = emailOne_.find(myArray[i]); 会找到 @gmail.com,即使输入的电子邮件地址是 foo@gmail.com.uk,这可能不是您想要的。
  • 如果 myArray 中的第一个条目不匹配,您 break 退出并且不测试下一个条目。
  • 如果第一个条目一个匹配项,你不会break,所以你继续尝试myArray 中的下一个字符串当然不会匹配 - 然后你就跳出来了。

因此目前无法获得有效匹配。 break只有在找到有效匹配时才输出,您应该能够得到正确的结果。

带有一些简化建议的示例:

#include <iostream>
#include <string>

int main() {
    const std::string myArray[] = {"@gmail.com", "@yahoo.com"};

    std::string emailOne_;

    for(;;) {
        std::string emailTwo_;
        std::cout << "Email: ";
        std::cin >> emailOne_;
        std::cout << "Re-enter email: ";
        std::cin >> emailTwo_;

        // simplify comparisons:
        if(emailOne_ != emailTwo_) {
            std::cerr << "\t[*] ERROR: EMAILS DO NOT MATCH\n\n";
            continue; // back to entering email
        }

        bool valid = false;

        // Use range-based for loops to simplify looping over arrays:
        for(const std::string& end : myArray) {

            // check if the end of emailOne_ is equal to `end` by comparing
            // a substring of emailOne_ with the same length as end, with end:

            if(emailOne_.size() > end.size() &&   // must be long enough
               emailOne_.substr(emailOne_.size() - end.size()) == end)
            {
                valid = true;
                break;
            }
        }

        // check the valid state after the loop:
        if(!valid) {
            std::cerr << "\t[*] ERROR: EMAILS MUST HAVE @gmail.com or @yahoo.com\n";
        } else {
            break; // a valid email address was found.
        }
    }

    std::cout << emailOne_ << " is a valid address\n";
}