首页 > 解决方案 > 尝试使用 C++ 从列表中打印无效的电子邮件地址?

问题描述

我正在尝试从电子邮件地址列表中打印无效电子邮件地址列表(其中包含空格且没有 @ 或 .)。该列表有一些带有空格的电子邮件地址,并且没有“@”或“。” 但它仍然没有打印任何东西。

    //Declaring boolean variables
    bool atPresent;
    bool periodPresent;
    bool spacePresent;
    
    string emailid = someemailfrom a list;
    atPresent = false;
    periodPresent = false;
    spacePresent = false;
    
    //looking for @
    size_t foundAt = emailid.find('@');
    if (foundAt != string::npos) {
        atPresent = true;
    }
    
    //looking for '.'
    size_t foundPeriod = emailid.find('.');
    if (foundPeriod != string::npos) {
        periodPresent = true;
    }
    
    //looking for ' '
    size_t foundSpace = emailid.find(' ');
    if (foundSpace != string::npos) {
        spacePresent = true;
    }
    
    //checking to see if all conditions match
    if ( (atPresent == false) && (periodPresent == false) && (spacePresent == true)) {
        cout << emailid << endl;
    }

标签: c++stringboolean-logic

解决方案


(atPresent == false) && (periodPresent == false) && (spacePresent == true)

是错的。仅当满足无效地址的所有三个条件时,它才是正确的。但是,只要满足至少一个标准,地址就无效。这将是

(atPresent == false) || (periodPresent == false) || (spacePresent == true)

并简化:

!atPresent || !periodPresent || spacePresent

推荐阅读