当接受C中的命令行参数时,有没有办法确保字符串只包含字母(即没有字母数字或符号)而不转换为int?这有内置功能吗?
int
main(int argc, char *argv[])
{
char *input = argv[1];
if (/* input contains anything but upper and lowercase letters */)
return 1;
...
}
Run Code Online (Sandbox Code Playgroud)
对于"只信",使用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;
}
Run Code Online (Sandbox Code Playgroud)
请注意,isalpha()将根据当前区域设置返回不同的结果.您可能想要使用isalnum()(字母数字)而不仅仅是字母; 你可以用islower()或更准确isupper().等等.