It always return FALSE even though every single variable satisfies conditions

528 views c
-1

I don't understand why it always returns FALSE even though every single variable satisfies conditions. I've tried to change the characters in the conditions to ascii numbers but it can not solve the problem. Any help, Thanks a lot.

I want to check every variable in an array if one of them is dissimilar to the characters in the alphabet or "SPACE" or ".", the function will return False.

bool KiemTraTenSinhVien(char ten[])
{
    for (int i = 0; i < strlen(ten); i++)
    {
        if (ten[i] == (char)" " || ten[i] == (char)".")
        {
        }
        else if (ten[i] >= (char)"a" && ten[i] <= (char)"z")
        {
        }
        else if (ten[i] >= (char)"A" && ten[i] <= (char)"Z")
        { 
        }
        else
        {
            return false;
        }
    }
    return true;
}

I also try this but the problem still be unsolved

bool KiemTraTenSinhVien(char ten[])
{
    for (int i = 0; i < strlen(ten); i++)
    {
        if (ten[i] == ' ' || ten[i] == '.')
        {
        }
        else if (ten[i] >= 'a' && ten[i] <= 'z')
        {
        }
        else if (ten[i] >= 'A' && ten[i] <= 'Z')
        { 
        }
        else
        {
            return false;
        }
    }
    return true;
}

answered question

use single quotes as ten[i] == ' '. similar for other comparisons.

thank you. I'try it now

It does not work @madjaoue

else if (ten[i] >= 'a' && ten[i] <= 'a') will be false for every character except for 'a'.

but when I change 'a' to 97 (the number of it in the ascii table) and 'z' to 122, the function still returns FALSE

1 Answer

2

Use an array of valid characters and test with strchr.

bool KiemTraTenSinhVien(char ten[])
{
    char valid[] = " .abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int len = strlen ( ten);
    for (int i = 0; i < len; i++)
    {
        if ( ! strchr ( valid, ten[i]))
        {
            return false;
        }
    }
    return true;
}

posted this

Have an answer?

JD

Please login first before posting an answer.