【发布时间】:2020-09-09 10:00:21
【问题描述】:
我的代码中一直出现此错误。它工作正常,但在我在plaintext 中输入的第 8 个字符之后,它就像公式出错或计算中的某些内容发生了变化,并且它开始加密为错误的字符。
请有人帮我弄清楚我做错了什么?
我已经尝试过使用调试器,但我不明白出了什么问题。
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
char upperciphertext (char text);
char lowerciphertext(char text);
int key;
char cyphertext[] = "ciphertext: ";
int main(int argc, string argv[])
{
//check if command line arg. is inputed and not more than 1
if (argc > 2 || argc < 2)
{
printf("Usage: ./caesar key\n");
return 1;
}
//check if characters are digits
for (int i = 0; argv[1][i] != '\0'; i++)
{
if (isdigit(argv[1][i]))
{
//convert commandline argument to int
}
else
{
printf("Usage: ./caesar key\n");
return 1;
}
}
key = atoi(argv[1]);
char * plaintext = get_string("plaintext: \n");
//loop to iterate over each character in text
for (int i=0; plaintext[i] != '\0'; i++)
{
//turn uppercase letters to uppercase ciphertext
if (isalpha(plaintext[i]) && isupper(plaintext[i]))
{
char cytext = upperciphertext(plaintext[i]);
strncat(cyphertext, &cytext, 1);
}
//turn lowercase letters to lowercase ciphertext
else if (isalpha(plaintext[i]) && islower(plaintext[i]))
{
char lowcytext = lowerciphertext(plaintext[i]);
strncat(cyphertext, &lowcytext, 1);
}
else
{
strncat(cyphertext, &plaintext[i], 1);
}
}
printf("%s\n", cyphertext);
}
//function to cipher uppercase characters
char upperciphertext (char text)
{
int alphaindex, cipher, ciphertext;
char ctext;
alphaindex = text - 65;
cipher = (alphaindex + key) % 26;
ciphertext = cipher + 65;
ctext = ciphertext;
return ctext;
}
//function to cipher lowercase characters
char lowerciphertext(char text)
{
int alphaindex, cipher, ciphertext;
char ctext;
alphaindex = text - 97;
cipher = (alphaindex + key) % 26;
ciphertext = cipher + 97;
ctext = ciphertext;
return ctext;
}
【问题讨论】:
-
在
for (int i=0; plaintext[i] != '\0'; i++)循环之后打印plaintext[i]会得到什么? -
我得到了我输入的确切文本或字符
-
嗨,您可能想先阅读这篇文章:ericlippert.com/2014/03/05/how-to-debug-small-programs。之后,就 C 中令你感到惊讶的部分提问。不要担心有一些 C 块直到今天我都觉得很可怕。
-
看
char cyphertext[] = "ciphertext: ";:你想像为数组cyphertext[]预留了多少空间?您希望用strncat(cyphertext, &cytext, 1);添加的文本更写或最好覆盖的地方?
标签: c computer-science cs50