即使每个变量都满足条件,它也始终返回FALSE

时间:2018-11-03 23:27:37

标签: c

即使每个变量都满足条件,我也不明白为什么总是返回FALSE。我试图将条件中的字符更改为ascii数字,但无法解决问题。任何帮助,非常感谢。

我想检查数组中的每个变量,如果它们中的一个与字母或“ SPACE”或“。”中的字符不同,则该函数将返回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;
}

我也尝试这样做,但是问题仍然没有解决

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;
}

1 个答案:

答案 0 :(得分:1)

使用有效字符数组并使用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;
}