在 C 中接受命令行参数时,有什么方法可以确保字符串只包含字母(即没有 letters 数字或符号)而不转换为 int?有内置函数吗?
int
main(int argc, char *argv[])
{
char *input = argv[1];
if (/* input contains anything but upper and lowercase letters */)
return 1;
...
}
最佳答案
对于“仅字母”,使用 isalpha()
来自 <ctype.h>
.当然,你必须将它包装成一个函数:
#include <stdbool.h>
#include <ctype.h>
bool all_alpha(const char *str)
{
char c;
while ((c = *str++) != '\0')
if (!isalpha(c))
return false;
return true;
}
请注意 isalpha()
将根据当前语言环境返回不同的结果。你可能想使用 isalnum()
(字母数字)而不仅仅是字母;你可以用 islower()
更精确或 isupper()
.等等
关于检查 C 字符串中的某些字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7493086/