我一直在try 做CS50的S课程(这是我第一次接触C语言,请多多包涵),并解决了替换问题.我已经坚持了一段时间了. 这是我的错误代码:
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int check(string str);
int main(int argc, string argv[])
{
if(argc < 1 || argc > 2)
{
printf("Usage: ./substitution key");
return 1;
}
string key = argv[1];
if(check(key) == 1)
{
return 1;
}
string plaintext = get_string("plaintext:");
int lenght = strlen(plaintext);
char ciphertext[lenght + 1];
for(int i = 0; i <= lenght; i++)
{
if(islower(plaintext[i]))
{
plaintext[i] -= 97;
ciphertext[i] = key[(int)plaintext[i]];
if(isupper(ciphertext[i]))
{
ciphertext[i] = tolower(ciphertext[i]);
}
}
if(isupper(plaintext[i]))
{
plaintext[i] -= 65;
ciphertext[i] = key[(int)plaintext[i]];
if(islower(ciphertext[i]))
{
ciphertext[i] = toupper(ciphertext[i]);
}
}
}
printf("ciphertext:%s", ciphertext);
}
int check(string str)
{
//controlle del numero di lettere, che i caratteri della chiave non siano ripetuti o numerici hahahahah lol
char alphabet[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int count[26] = { 0 };
if(strlen(str) != 26)
{
printf("Key must contain 26 characters.");
return 1;
}
for(int i = 0; i < 25; i++)
{
if(isalpha(str[i]) == 0)
{
return 1;
}
str[i] = (char)tolower(str[i]);
for(int j = 0; j < 25; j++)
{
if(str[i] == alphabet[j])
{
count[j] += 1;
}
}
}
for(int i = 0; i < 25; )
{
if(count[i] != 1)
{
return 1;
}
}
return 0;
}
主要问题是,通过存储argv[1]将其作为字符串处理似乎是不可能的,因为无论何时我运行程序,它都会无休止地运行.
这是我在调试控制台上得到的分段错误:
Program received signal SIGSEGV, Segmentation fault. __strlen_evex () at ../sysdeps/x86_64/multiarch/strlen-evex.S:77
个
当我try 调试时,它显示在try 使用strlen()获取密钥长度时出现分段错误.另外,在调试时,它显示key已存储0x0,所以可能我不知何故也错误地将argv[1]赋值给key.我认为这可能是因为argv[1]不是以一个
空字符,但我不确定,因为我只知道c的基本知识.