c - CS50/Substitution -为什么tolower()函数在我的代码中不起作用? &g



谁能解释一下如果我切换

// 3.3 Must not contained repeated letters |
if (toupper(argv[1][j] == toupper(argv[1][k])))

if (tolower(argv[1][j] == tolower(argv[1][k])))

为什么它不再工作了,即使字母可能是相同的,计算机不能识别它?

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc,string argv[])  
{
int count_key_char = 0;
int count_repeated_char = 0;
//Exactly 1 command line argument
if (argc == 2)
{
//Must all be letters
for (int i = 0; i < strlen(argv[1]); i++)
{
if (isalpha(argv[1][i]))
{
count_key_char++;
}
}
// 3.3 Must not contained repeated character/s
for (int j = 0, n = strlen(argv[1]); j < n; j++)
{
for (int k = j + 1; k < n; k++)
{
if (toupper(argv[1][j] == toupper(argv[1][k])))
{
count_repeated_char++;
}
}
}
// Must be 26 characters (Fail criteria)
if (strlen(argv[1]) != 26)
{
printf("Key must contain 26 characters.n");
return 1;
}
// Must be all letters  (Fail criteria)
else if (count_key_char != strlen(argv[1]))
{
printf("Key must only contain alphabetic characters.n");
return 1;
}
// Must not contained repeated character/s (Fail criteria)
else if (count_repeated_char != 0)
{
printf("Key must not contain repeated characters.n");
return 1;
}
// 4. Get plaintext; Prompt user for plaintext
else
{
string plaintext = get_string("Plaintext: ");
printf("ciphertext: ");
for (int w = 0; w < strlen(plaintext); w++)
{
// If character are letter & uppercase
if (isalpha(plaintext[w]) && isupper(plaintext[w]))
{
int upper = (plaintext[w] -65);
printf("%c", toupper(argv[1][upper]));
}
// If character are lower & lowercase
else if (isalpha(plaintext[w]) && islower(plaintext[w]))
{
int lower = (plaintext[w] - 97);
printf("%c", tolower(argv[1][lower]));
}
// If character are not letter, print as it is
else
{
printf("%c", plaintext[w]);
}
}
printf("n");
return 0;
}
}
else
{
printf("Usage: ./substitution keyn");
return 1;
}
}

这一行有一个错位的父括号)

if (toupper(argv[1][j] == toupper(argv[1][k])))

如果字母是小写的,toupper将失败;如果字母是大写的,tolower将失败。它正在计算

argv[1][j] == toupper(argv[1][k])

如果两个字符是相同的大写字母,则返回1 (true)。如果键以小写形式输入,则line将返回0 (false),并且程序将不认为它是重复字符。

toupper参数用圆括号括起来,问题就解决了。

相关内容

  • 没有找到相关文章

最新更新