如何检查C中的某些字符

时间:2009-09-25 22:35:19

标签: c

我正在编写一个脚本,我需要确保它们只放入某些字符。这些包括“x”,“/”,“+”,“ - ”,“%”(基本数学运算符),-z和每个数字的每个字母。我在下面有以下内容,只检查alpha和数字。如何检查是否只使用了某个,以及其他所有内容,例如“&”或“>”,是否正确处理错误?

//check to see if user has input an incorrect symbol or letter
    if (isalpha(symbol) || isalnum(symbol)) 
    {
        printf("You must enter a math operator, not a letter or number. \n \n");
    }
    else {//move along nothing to see here
    }

6 个答案:

答案 0 :(得分:9)

创建一个包含所有允许字符的字符串,然后检查字符串。

char* ok = "/+-*%";

if (isalpha(symbol) || isalnum(symbol) || strchr(ok, symbol) == NULL) 
{
    printf("You must enter a math operator, not a letter or number. \n \n");
}
else {//move along nothing to see here
}

答案 1 :(得分:3)

编写您自己的isMathOperator函数,该函数对您想要允许的符号返回true。

答案 2 :(得分:1)

我认为你必须自己检查每个输入字符。 strchr可以提供帮助

/* code untested. I don't have a compiler available at the moment */
/* input = "123 / 14 + x - 5"; */
char *pinput = input;
while (*pinput) {
    if (!strchr("+-*/% abcdefghijklmnopqrstuvwxyz0123456789", *pinput)) {
        /* unacceptable character */
        break;
    }
    ++pinput;
}
if (*pinput != '\0') {
    fprintf(stderr, "Invalid input\n");
}

答案 3 :(得分:1)

在C语言中对这类问题的一般回答是,您可以使用精心设计的字符串处理语言在幕后完成做的事情:您检查每个字符并在开放代码中处理它。

话虽如此,现在有两种处理每个角色的方法:

  • 使用多方if或索引一串有效字符,可能是strchr(3)
  • 使用查找表,即x['a'] = 1, if(x[i]) ...

说过 ,有一种混合方法,它使用预构建的查找表,它是C89之前的每个C库的一部分,称为ctype.h。可以在isalpha(3)下找到此页面,在unix上使用man 3 isalpha,在Windows下使用google或msdn。

答案 4 :(得分:0)

如果它是一个字符,那么你可以做这样的事情

if(charVariable == '+')

这些必须是单引号。

答案 5 :(得分:0)

实现TheUndeadFish的想法:

int isMathOperator(int c)
{
    static char symbols[257] =
    {
        ['+'] = 1, ['-'] = 1, ['/'] = 1, ['x'] = 1,
        ['='] = 1, ['%'] = 1, ...
    };
    assert(c == EOF || (c & 0xFF) == c);
    return((c == EOF) ? 0 : symbols[c]);
}

请注意,与<ctype.h>中的isxxxx()宏/函数一样,此函数接受任何有效的8位字符或EOF。它使用C99机制初始化数组的特定元素。