分段错误:布尔表达式
Segmentation fault: boolean expression
我遇到错误 "Segmentation fault"。我认为它与 isdigit(argv[i]) 行有关,但不明白为什么。
#include <stdio.h>
#include <cs50.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
//implement commandline arguments
int main(int argc, string argv[])
{
//convert string element in array to integer
int key = atoi(argv[1]);
//check that user input for key is no more than 2 memory spots, not a negative number and a single input
if (argc != 2 || key < 0 || isdigit(argv[1]))
{
printf("useage: ./caesar key\n");
return 1;
}
else
{
string plaintext = get_string("plaintext: ");
printf("ciphertext: %s \n", plaintext);
return 0;
}
}
假设您确实有一个有效的字符串作为参数传递,那么 argv[1]
指的是 整个字符串 。要检查该字符串的第二个字符是否为数字,您需要进一步'dereference'该字符串,并使用:isdigit(argv[1][1])
。或者,对于该字符串的 first 字符,使用 argc[1][0]
(或 *argv[1]
)。
我遇到错误 "Segmentation fault"。我认为它与 isdigit(argv[i]) 行有关,但不明白为什么。
#include <stdio.h>
#include <cs50.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
//implement commandline arguments
int main(int argc, string argv[])
{
//convert string element in array to integer
int key = atoi(argv[1]);
//check that user input for key is no more than 2 memory spots, not a negative number and a single input
if (argc != 2 || key < 0 || isdigit(argv[1]))
{
printf("useage: ./caesar key\n");
return 1;
}
else
{
string plaintext = get_string("plaintext: ");
printf("ciphertext: %s \n", plaintext);
return 0;
}
}
假设您确实有一个有效的字符串作为参数传递,那么 argv[1]
指的是 整个字符串 。要检查该字符串的第二个字符是否为数字,您需要进一步'dereference'该字符串,并使用:isdigit(argv[1][1])
。或者,对于该字符串的 first 字符,使用 argc[1][0]
(或 *argv[1]
)。