有什么办法可以缩短这个 if 语句吗?

Is there a way I can shorten this if statment?

我有一个非常大的 if 语句,它看起来不顺眼,而且效率不高。

我正在制作一个程序(取决于用户的输入)运行特定的代码块,例如,如果用户输入 'a' 程序运行一个代码,向文件添加一些东西等。顺便说一句,这是在一个 do-while 语句中(虽然我不知道这是否相关)。

else if(ansr != 'a' && ansr != 'A' && ansr != 'r' && ansr != 'R' && ansr != 's' && ansr != 'S' && ansr != 'e' && ansr != 'E')
{
    printf("Invalid input!\n");
}

如您所见,这是一个非常长的 if 语句,我希望它更短一些。谢谢

根据 ansr 的大小写是否重要,在 if 语句之前转换为小写将使所需的检查量减少一半。

嗯,什么例子,随便什么。

为什么不使用 strchrstrchr returns 指向字符串中字符的指针(如果找到),否则为 NULL。

else if (strchr("aArRsSeE", ansr) == NULL)
{
    printf("Invalid input!\n");
}

我会选择:

switch(tolower(ansr)) {
case 'a':
case 'r':
case 's':
case 'e':
    do_stuff();
    break;
/* other cases here */
}

或者你可以使用更多的库函数如:

if (strchr("ares", tolower(ansr)) {
    do_stuff();
}

strchr 函数正在给定字符串中搜索给定字符,如果不存在则 returns NULL (或指向它第一次出现的指针,但它不存在)我们在这里感兴趣的用例)

  • 这是假设 ansrunsigned charEOF 的范围内。否则 tolower 的行为是未定义的。

为了回答您的问题,我个人会使用 switch statement. It is easy to use and easy to read. Another thing which would make your code slightly more readable is using toupper。 这是一个例子:

#include <stdio.h>
#include <ctype.h>

int main ()
{
    char inp = 'i';
    char ansr = toupper(inp);
    switch(ansr) {
        case 'A' :
            // Do something
            break;
        case 'R' :
            // Do something
            break;
        case 'S' :
            // Do something
            break;
        case 'E' :
            // Do something
            break;
        default :
            printf("Invalid input!\n");
    }
    return 0;
}

您似乎正在尝试编写一个 else if 案例来捕获您 支持的输入字符。 else 案例非常适合这种情况:

...
char input;
//get your input
if (input == 'A' || input == 'a')
    DoA();
else if (input == 'R' || input == 'r')
    DoR();
else if (input == 'S' || input == 's')
    DoS();
else if (input == 'E' || input == 'e')
    DoE();
else
    DoInvalidInput();

或者,如果您使用 tolower(),您可以将其放在 switch 语句中:

char lowerChar = tolower((unsigned char)input);
switch (lowerChar)
{
    case 'a': DoA(); break;
    case 'r': DoR(); break;
    case 's': DoS(); break;
    case 'e': DoE(); break;
    default: DoInvalidInput(); break;
}