【发布时间】:2022-01-24 03:13:42
【问题描述】:
我在 CS50 上执行 Pset2 cesear 并且在运行程序时不断遇到分段错误。为什么我得到它,什么是分段错误。 ..................................................
#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
int main(int argc, string argv[])
{
string key = argv[argc-1];
int keylen = strlen(key);
string plaintext = get_string("Enter the plaintext: ");
int ciphertext [strlen(plaintext)];
int move[strlen(key)];
int counter = 0;
for (counter = 0; counter < 26; counter++)
{
if ((plaintext[counter] > 96) && (plaintext[counter] < 123))
{
move[counter] = (plaintext[counter]) - 97 ;
ciphertext[counter] =key[move[counter]];
}
else if (plaintext[counter] > 64 && plaintext[counter] < 91)
{
move[counter] = plaintext[counter] - 65;
ciphertext[counter] =key[move[counter]];
}
else ciphertext[counter] = plaintext[counter];
}
for (int loop = 0; loop < strlen(plaintext); loop++)
{
printf("%c\n", ciphertext[loop]);
}
}
【问题讨论】:
-
您缺少包含。
-
所以一个问题,您显然是在要求用户为他们的输入字符串输入 准确 26 个字符?对此很有信心,是吗?如果我只是输入文本“否”怎么办?你认为从 0..25 开始的循环会针对
plaintext[counter]做什么?硬编码的 26 是从哪里来的(为什么)? -
get_string()是做什么的?没有stackoverflow.com/help/mcve,你不可能得到有用的答案 -
而不是
if( plaintext[counter] > 64 ),写成if( plaintext[counter] >= 'A')更具可读性。对于所有其他硬编码值也是如此。总是写'A'而不是65,'a'而不是97等等。 -
你为什么要迭代
for (counter = 0; counter < 26; counter++)而不是从 0 到 strlen(plaintext)?
标签: c error-handling cs50