简体   繁体   English

如果语句导致循环无法完全运行? C ++

[英]If statement causing loop to not fully run? C++

for (int k = 0; k != s.size(); k++)
{
    if (s[k] == 'A' || s[k] == 'B' || s[k] == 'C' || s[k] == 'D' )
        return true; 
    else 
        return false;
}

I am trying to check to see if the entered string contains any characters other than these. 我正在尝试检查输入的字符串是否包含除这些以外的任何字符。 If it does, I want it to return false. 如果是这样,我希望它返回false。 However, When I put in a string like "ABCEDF" it returns true. 但是,当我输入“ ABCEDF”之类的字符串时,它将返回true。 It seems like it's only checking the first character/index. 似乎只检查第一个字符/索引。 How can I use for loops and if statements to check if the entered string meets the correct criteria and returns true/false accordingly? 如何使用for循环和if语句检查输入的字符串是否符合正确的条件,并相应地返回true / false?

The problem is that you are really checking whether the very first char is one of those listed in the if . 问题是您真的在检查第一个字符是否是if列出的字符。 The error is algorithmic because in order to decide whether the string contains chars other than ABCD you have to at least read every single char of the input string. 该错误是算法错误的,因为要确定字符串是否包含除ABCD以外的其他字符,您必须至少读取输入字符串中的每个字符。 This translates to: return true inside the loop if you read anything different from ABCD . 转换为:如果您读取的内容不同于ABCD则在循环内返回true。 If you have read the whole string and you still have not returned, well, guess what, the string is only made of ABCD s so you can return false! 如果您已阅读了整个字符串,但仍未返回,那么,请猜猜,该字符串仅由ABCD组成,因此您可以返回false!

Plus, if you want to check whether the string contains any char other than ABCD you should check whether s[k]!=A && s[k]!=B && s[k]!=C && s[k]!=D 另外,如果要检查字符串是否包含除ABCD以外的任何字符,则应检查s[k]!=A && s[k]!=B && s[k]!=C && s[k]!=D

Something, as follows, should work: 某些操作如下:

bool otherThanABCD(const string& s){
    for (int k = 0; k != s.size(); k++){
        if (!(s[k] == 'A' || s[k] == 'B' || s[k] == 'C' || s[k] == 'D') )    
    // there is a char which is not ABC or D!
          return true; 
   }
    // I have read the whole string, but still nothing other than ABC and D
 return false;
}

If the condition is true you return true . 如果条件为true ,则返回true If the condition is false you return false . 如果条件为false ,则返回false There is no branch in the condition where you do not return . return的情况下,没有分支。

Your code is equivalent to 您的代码等同于

for (int k = 0; k != s.size(); k++)
{
    return (s[k] == 'A' || s[k] == 'B' || s[k] == 'C' || s[k] == 'D' );
}

In other words, you return unconditionally. 换句话说,您无条件返回。


Without knowing exactly what you want to do or what you're doing, I guess you might want something like this instead: 在不确切知道您想做什么或正在做什么的情况下,我您可能想要这样的事情:

for (int k = 0; k != s.size(); k++)
{
    if (s[k] == 'A' || s[k] == 'B' || s[k] == 'C' || s[k] == 'D' )
        return true;
}

return false;

Where you return false only after the loop. 只有循环之后才返回false。

You really do not need loops and a bunch of if statements to do this task you can write a simple function that'll do this for you. 您确实不需要循环和一堆if语句来执行此任务,您可以编写一个简单的函数来为您完成此任务。 Check this bit of code out! 检查一下这段代码!

#include <string>
#include <iostream>

// This checkString function is all you really need!
bool checkString( const std::string& stringToCheck, const std::string& checkAgainstThis ) {
    if ( stringToCheck.empty() || checkAgainstThis.empty() ) {
        // throw exception - both strings have nothing in them!
    }

    std::basic_string<char>::size_type firstIndex = stringToCheck.find_first_not_of( checkAgainstThis );
    if ( firstIndex == std::string::npos ) {
        return true;  // Didn't find anything.
    }

    return false;  // Found something other than.
}

// helper functions to display messages in main function - these are not required for
// the above function; just makes the main function cleaner and easier to read

void displayCheckingMessage( const std::string& a, const std::string& b ) {
    std::cout << "Checking string " << a << "\nto see if it contains any character other than this set: " << b << ".\n";
}

void displayResultMessage( bool condition, const std::string& str ) {
    if ( condition ) {
        std::cout << "Did not find any other characters.\n\n";
    } else {
        std::cout << "Found something other than " << str << ".\n\n";
    }
}

int main() {    
    std::string stringToCheck( "ABCADCDABC" );
    const std::string checkAgainstThis( "ABCD" );

    displayCheckingMessage( stringToCheck, checkAgainstThis );
    displayResultMessage( checkString( stringToCheck, checkAgainstThis ), checkAgainstThis );

    stringToCheck.clear();
    stringToCheck = std::string( "ABCDE" );
    displayCheckingMessage( stringToCheck, checkAgainstThis );
    displayResultMessage( checkString( stringToCheck, checkAgainstThis ), checkAgainstThis );

    stringToCheck.clear();
    stringToCheck = std::string( "AAABBBCCCDDDAAABBDDCCSSRRAASSGGSS" );
    displayCheckingMessage( stringToCheck, checkAgainstThis );
    displayResultMessage( checkString( stringToCheck, checkAgainstThis ), checkAgainstThis );

    stringToCheck.clear();
    stringToCheck = std::string( "AAAAAAAAAAAAAAAAABBBBBBBBBBBBBAAAAAAAAAAAAAAACCCCCCCCCCCCDDDDDDDDDDD" );
    displayCheckingMessage( stringToCheck, checkAgainstThis );
    displayResultMessage( checkString( stringToCheck, checkAgainstThis ), checkAgainstThis );

    stringToCheck.append( "XABCD" );
    displayCheckingMessage( stringToCheck, checkAgainstThis );
    displayResultMessage( checkString( stringToCheck, checkAgainstThis ), checkAgainstThis );

    // try a different set
    std::cout << "\n";
    const std::string checkAgainstThis2( "XYZ" );
    displayCheckingMessage( stringToCheck, checkAgainstThis2 );
    displayResultMessage( checkString( stringToCheck, checkAgainstThis2 ), checkAgainstThis2 );

    stringToCheck.clear();
    stringToCheck = std::string( "XYZXYZXYZXYZ" );
    displayCheckingMessage( stringToCheck, checkAgainstThis2 );
    displayResultMessage( checkString( stringToCheck, checkAgainstThis2 ), checkAgainstThis2 );

    stringToCheck.append( "8?#XYZXYSAZC" );
    std::cout << "\n" << stringToCheck << "\n";
    displayCheckingMessage( stringToCheck, checkAgainstThis2 );
    displayResultMessage( checkString( stringToCheck, checkAgainstThis2 ), checkAgainstThis2 );

    return 0;
}

With this simple function you can check any first string to see if it contains any character other than the set of characters you want to check against from the second string. 使用此简单功能,您可以检查任何第一个字符串以查看其是否包含除第二个字符串中要检查的字符集以外的任何字符。 This also prevents you from having to "hard code" characters in if statement conditionals. 这也可以防止您在if语句有条件的情况下必须对字符进行“硬编码”。 This also gives you the added bonus to compare any string against a set of determined characters. 这也给您额外的好处,可以将任何字符串与一组确定的字符进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM