我正在为CS50 PSET 2 'Substitution'写一个程序。当我在命令行中运行./substitution时,不是打印假定的“使用错误”,而是打印一个分段错误。此外,当我尝试使用debug 50时,它会暂停(见下文),这再次显示Segmentation fault,这不允许我使用调试器。
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main(int argc, string argv[])
{
string key = argv[1];
int length = strlen(key); // LINE WHERE DEBUGGER GETS PAUSED ON
// prints a usage error if a user inputs no key, or more than one key
while (argc != 2)
{
printf("Usage: ./substituion key\n");
return 1;
}
// prints an error if a user inputs a key that isn't 26 characters
while (length != 26)
{
printf("Key must contain 26 characters.\n");
return 1;
}
int score = 0;
// loops through key
for (int i = 0; i < length; i++)
{
// if the current character isn't a part of the alphabet, an error is printed
if (key[i] < 'A' || key[i] > 'z')
{
printf("Key must contain only alphabetical letters\n");
return 1;
}
// if the current character is lowercase, it is subtracted by 32 to make is uppercase, and that (ASCII) value is added to score
if (islower(key[i]))
{
score += key[i] - 32;
}
// if the current character is uppercase, its ASCII value is added to score
if (isupper(key[i]))
{
score += key[i];
}
}
// if each uppercase letter of the alphabet's ASCII value are added together, it equals 2015;
// if that added values of the key do not equal 2015, that means there is a repeated letter, which prints an error message
while (score != 2015)
{
printf("Key must contain each letter exactly once\n");
return 1;
}
string plainText = get_string("plaintext: ");
printf("ciphertext: ");
for (int j = 0; plainText[j] != '\0'; j++)
{
char plainLetter = plainText[j];
//printf("plain: %c\n", plainLetter);
if (isupper(plainLetter))
{
printf("%c", toupper(key[plainLetter - 'A']));
}
if (islower(plainLetter))
{
printf("%c", tolower(key[plainLetter - 'a']));
}
if (isdigit(plainLetter) || ispunct(plainLetter) || isspace(plainLetter))
{
printf("%c", plainLetter);
}
}
printf("\n");
return 0;
}
我不知道该怎么办,因为我查找了什么是分段故障,但我无法将其与我的问题相关联。我正在考虑重写整个程序,而不声明键长度的变量,但我也想知道这个“分段错误”的原因。
2条答案
按热度按时间vybvopom1#
移动
下面
似乎修复了它。
hrysbysz2#
首先你应该检查argc的值,如果不等于2,然后返回程序。
我认为最好使用
if(argc != 2)
而不是while (argc != 2)
来检查argc的值,如果天气等于2。与
while (length != 26)
相同,使用if(length != 26)
。与
while (score != 2015)
相同,使用if(score != 2015)
所以我的答案是: