【发布时间】:2014-07-19 13:43:58
【问题描述】:
我被困在这个例子中。每当我输入关键字“培根”时,我都会得到错误的答案。 知道为什么会这样吗?我找不到错误,我已经尝试了很多。 你能帮帮我吗?
当我运行这个: ./vigenere bacon 并输入文本 Meet me at the park at eleven am 时,答案应该是 Negh zf av huf pcfx bt gzrwep oz,但我得到的是 Negh ne og tjs qaty bt syfvgb bm
更新:我按照 cmets 的建议进行了一些更改,但仍然遇到同样的问题。
#include<cs50.h>
#include<ctype.h>
#include<stdio.h>
#include<string.h>
int main(int argc, char *argv[])
{
//check if it has only two values
if (argc != 2)
{
printf("Usage: ./vigenere keyword\n");
return 1;
}
// check that every letter of keyword is alphabetic
char *keyword = argv[1];
int keylen = strlen(keyword);
for (int i = 0, n = keylen; i < n; i++)
{
if(!isalpha(keyword[i]))
{
printf("alphabetic keyword only!!!\n");
return 1;
}
if(isalpha(keyword[i]))
{
// if a letter of keyword is uppercase
if (isupper(keyword[i]))
{
keyword[i] = keyword[i] - 'A';
}
// if a letter of keyword is lowercase
if (islower(keyword[i]))
{
keyword[i] = keyword[i] - 'a';
}
}
}
char *text = GetString();
for (int i = 0, n = strlen(text); i < n; i++)
{
if (isalpha(text[i]))
{
// if plaintext letter uppercase then...
if (isupper(text[i]))
{
text[i] = ((text[i] - 'A') + (keyword[i % keylen])) % 26 + 'A';
printf("%c",text[i]);
// ^^^^^^ ----> repeat the pattern
}
// if plaintext letter lowercase then ...
if (islower(text[i]))
{
text[i] = ((text[i] - 'a') + (keyword[i % keylen])) % 26 + 'a';
printf("%c",text[i]);
}
}
// if no letters in plaintext then ...
if (!isalpha(text[i]))
{
text[i] = text[i];
printf("%c",text[i]);
}
}
printf("\n");
}
【问题讨论】:
-
“错误答案”是什么意思?您期望发生什么,实际发生了什么?
-
当我输入参数 ./vigenere bacon 和文本 上午 11 点在公园见我 答案应该是 Negh zf av huf pcfx bt gzrwep oz 而不是我得到 Nffu nf bu uif qbsl bu fmfwfo bn
-
keyword[i % strlen(keyword)]: 可能strlen转换为数字keyword后无法正常运行。 (例如关键字[i] = 关键字[i](当'a')-'a' == 0) -
所以我应该在循环之前声明 strlen(keyword) 吗?或者我应该避免使用 int cypher 而是使用 text[i]?
-
是的……快把我逼疯了……我现在要把头撞到墙上
标签: c encryption cs50 vigenere