问题描述
所以这个程序不会识别小写和大写字母数组中的字母。我已经浪费了太多时间试图弄清楚这一点,但我就是不明白。
它似乎只能识别“a”或“A”,但也并非总是如此。
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <ctype.h>
char ALPHABETLower[] = {'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'};
char ALPHABETUpper[] = {'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'};
string plaintext = "abcdefghijklmnoprstquvwyzABCDEFGHIJKLMnopRSTQUVWXYZ";
int i;
int j;
int main(void) {
for(i = 0; plaintext[i] != 0; i++) {
for(j = 0; plaintext[i] == ALPHABETUpper[j]; j++)
printf("%c\n",ALPHABETUpper[j]);
for(j = 0; plaintext[i] == ALPHABETLower[j]; j++)
printf("%c\n",ALPHABETLower[j]);
}
}
解决方法
首先,我认为您只需要在程序中包含 stdio.h
。
然后你有 string plainText = "...";
,但你应该有 char* plainText = "...";
,因为这是你在 C 语言中制作字符串的方式(我不知道你拥有的所有这些库是否都是为了制作 {{1} } 变量,但制作字符串的最简单和正确的方法就像我所做的那样,使用 string
)。
所以你在你的第一个 char
循环中 for
这样你可以在字符串结束时停止,但我认为这并不奏效,你能做到的最好方法是 {{1 }}。
您在其他 i = 0; plaintext[i] != 0; i++
循环中遇到了另一个问题。您试图在 i = 0; i < 52; i++
循环中创建条件语句,我认为这甚至不可能(在 for
循环中可以)。所以也许那些 for 循环应该是这样的:
for
,
所以我努力通过了,这是完整的工作版本。我之前的错误是让 for 循环无限运行,除非它可以在 ALPHABETUpper 中找到字符。
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <ctype.h>
char ALPHABETLower[] = {'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'};
char ALPHABETUpper[] = {'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'};
string plaintext;
int i;
int j;
int main(int argc,string argv[2]) {
for(i = 0; argv[1][i] != 0; i++)
if(argv[1][i] < 48 || argv[1][i] > 57) {
printf("Usage: ./caesar key\n");
return 1;
}
plaintext = get_string("Plaintext: \n");
for(i = 0; plaintext[i] != 0; i++) {
if(isalpha(plaintext[i]) == 0)
printf("%c",plaintext[i]);
for(j = 0; j < 26; j++) {
if(plaintext[i] == ALPHABETUpper[j])
printf("%c",ALPHABETUpper[(j + atoi(argv[1])) % 26]);
if(plaintext[i] == ALPHABETLower[j])
printf("%c",ALPHABETLower[(j + atoi(argv[1])) % 26]);
}
}
}