您不能使用
isdigit()
按照您在问题中的方式:它的参数必须是一个字符(所有类型的值
unsigned char
)或特殊负值
EOF
。传递字符串具有未定义的行为。
你的问题有很多可能的答案,这取决于你的意思
如果字符串是数字
:
-
检查指针是否指向字符串
s
仅由数字组成
strspn
定义于
<string.h>
:
if (*s && s[strspn(s, "0123456789")] == '\0') {
// s is not empty and only contains digits
}
-
检查它是否表示一个十进制整数,是否包含可选的租赁空格和可选的符号:
char *p;
strtol(s, &p, 10);
if (p != s && *p == '\0') {
// s contains the decimal representation of an integer
}
以下是使用
isdigit
正确地:
#include <cs50.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
bool string_is_number(const char *s) {
// reject empty string
if (*s == '\0') {
return false;
}
// skip digits
while (isdigit((unsigned char)*s)) {
s++;
}
// return true if all characters are digits
return *s == '\0';
}
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: ./caesar key\n");
return 1;
}
if (!string_is_number(argv[1])) {
printf("Usage: ./caesar key\n");
printf(" key must be a number\n");
return 1;
}
int key = strtol(argv[1], NULL, 10);
//...
}