Search code examples
c++arraysvoid

C++ how to cout once instead of multiple times in a for loop


void f3(string x){
    for (int i=0; i < x.length(); i++){

        if ('A'<=x[i] && 'z'>=x[i]){

            cout << "English Alphabet" << endl;
        }
        else {
            cout << "NOT English Alphabet" << endl;
            break;
        }
    }
}

how to get only one result (cout)? like "English Alphabet" instead of 4 times for "abcd".

examples:

gimme a string:
abcd
English Alphabet
English Alphabet
English Alphabet
English Alphabet

or

gimme a string:
abc!
English Alphabet
English Alphabet
English Alphabet
NOT English Alphabet

and if I input space the program does not work. How could I fix it? Thanks for the help!


Solution

  • Here two solutions:

    With a bool variable:

    void f3(string x)
    {
        bool notEnglish = false;
    
        for (int i=0; i < x.length(); i++)
        {
            if ( ('A' > x[i] || 'z' < x[i]) && x[i] != ' ' )
            {
                notEnglish = true;
                break;
            }
        }
    
        if (notEnglish) std::cout << "NOT ENGLISH" << std::endl;
        else std::cout << "ENGLISH" << std::endl;
    }
    

    Without a bool and with int as return value:

    int f3(string x)
    {
        for (int i=0; i < x.length(); i++)
        {
            if ( ('A' > x[i] || 'z' < x[i]) && x[i] != ' ' )
            {
                std::cout << "NOT ENGLISH" << std::endl;
                return -1;
            }
        }
    
        std::cout << "ENGLISH" << std::endl;
        return 1;
    }
    

    I prefer the second one since you have a feedback (the return value) of what is occured inside the function.