C - 替换密码:无法确认非重复字符

  • 本文关键字:确认 字符 替换 密码 c cs50
  • 更新时间 :
  • 英文 :


我遇到了CS50的替换密码问题。我不知道如何验证密钥。每当我传递一个26个字符的键作为命令行参数时,程序都会输出"您不得重复任何字符";即使钥匙上没有钥匙。我的程序正确地检查了键的长度和是否存在命令行参数。它只是不承认有效的非重复键。

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
bool validateKey(char key[]);
string substitute(char key[], string plaintext);
int main(int argc, string argv[]) {
if(strlen(argv[1]) == 26) { //key typed after prgm name will be used to encrypt data
if(validateKey(argv[1])) {

string plaintext = get_string("Plaintext: ");
string ciphertext = substitute(argv[1], plaintext);
printf("Ciphertext: %s", ciphertext);

}
}
else if(argv[1] == NULL) {
printf("Usage: ./substitution keyn");
}
else {
printf("Key must contain 26 characters.n");
}
}
bool validateKey(char key[]) {
for(int i = 0; i < 26; i++) {
if(!isalpha(key[i])) {
printf("Key must only contain alphabetic characters.n");
return false;
}
}
/*
an array of counters to keep track of how many times a letter occurs in the cipher
each counter should be set to 1 if key doesn't have repeating letters
*/
int cntr[26] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; 
for (int i = 0; i < 26; i++) {
key[i] = islower(key[i]); //make all the letters in the key lowercase to make it easier to work with
switch(key[i]) {
case 'a':
cntr[0] += 1;
case 'b':
cntr[1] += 1;
case 'c':
cntr[2] += 1;
case 'd':
cntr[3] += 1;
case 'e':
cntr[4] += 1;
case 'f':
cntr[5] += 1;
case 'g':
cntr[6] += 1;
case 'h':
cntr[7] += 1;
case 'i':
cntr[8] += 1;
case 'j':
cntr[9] += 1;
case 'k':
cntr[10] += 1;
case 'l':
cntr[11] += 1;
case 'm':
cntr[12] += 1;
case 'n':
cntr[13] += 1;
case 'o':
cntr[14] += 1;
case 'p':
cntr[15] += 1;
case 'q':
cntr[16] += 1;
case 'r':
cntr[17] += 1;
case 's':
cntr[18] += 1;
case 't':
cntr[19] += 1;
case 'u':
cntr[20] += 1;
case 'v':
cntr[21] += 1;
case 'w':
cntr[22] += 1;
case 'x':
cntr[23] += 1;
case 'y':
cntr[24] += 1;
case 'z':
cntr[25] += 1;
}
}
for(int i = 0; i < 26; i++) {
if(cntr[i] != 1) {
printf("Key must not contain repeated characters.n");
return false;
}
}
return true;
}
string substitute(char key[]) {
return "";
}

修复的方法是在每次增量之后添加一个break,这样你的case 'a'就不会执行case 'b'的代码。您还需要将islower调用更改为tolower(否则所有键值都变成01)。

也就是说,switch语句本身已经长得离谱了,实际上应该简化为一行:
cntr[tolower(key[i]) - 'a'] += 1;

,这是安全的,因为你已经检查了所有的输入字符通过isalpha

最新更新