https://cs50.harvard.edu/x/2023/psets/2/substitution/.
它给了我错误
将“char”传递给“const char*”类型的参数时,整数到指针转换不兼容;当我尝试编译程序时,它出现在第 36 行。
我该如何修复它?
#include <cs50.h>
#include <ctype.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
int main(int argc, string argv[])
{
string pt = get_string("plaintext: ");
int len = strlen(pt);
string ct;;
string key = argv[1];
int lenkey = strlen(key);
if (lenkey < 26)
{
printf("Key must contain 26 characters.");
}
else if (argc > 2)
{
printf("Usage: ./substitution key");
}
else if (argc < 2)
{
printf("Usage: ./substitution key");
}
string keyu;
string keyl;
// Key of uppercase
for (int i = 0; i < 26; i++)
{
if (isupper(key[i]))
{
keyu = strcat(keyu, key[i]);
}
else if (islower(key[i]))
{
keyu = strcat(keyu, toupper(key[i]));
}
}
// key of lowercase
for (int i = 0; i < 26; i++)
{
if (islower(key[i]))
{
keyl = strcat(keyl, key[i]);
}
else if (isupper(key[i]))
{
keyl = strcat(keyl, toupper(key[i]));
}
}
// create cyphertext
for (int i = 0; i < len; i++)
{
if (islower(pt[i]))
{
ct = strcat(ct, keyl[pt[i] - 97]);
}
else if (isupper(pt[i]))
{
ct = strcat(ct, keyu[pt[i] - 65]);
}
else
{
ct = strcat(ct, pt[i]);
}
}
}
以下是程序的重构版本,它基于加密密钥构建单词的加密版本。
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) /* Usual declaration with input parameters */
{
if (argc != 2)
{
printf("Usage: ./substitution key\n");
return 1;
}
char ct[30], pt[30], key[30], keyl[30], keyu[30]; /* Strings are character arrays */
int len;
//string pt = get_string("plaintext: ");
printf("plaintext: "); /* Common method to prompt for input */
len = scanf("%s", pt);
len = strlen(pt);
//string ct;;
//string key = argv[1];
strcpy(key, argv[1]); /* Common string copy method */
int lenkey = strlen(key);
if (lenkey < 26)
{
printf("Key must contain 26 characters.");
return 2;
}
//string keyu;
//string keyl;
// Key of uppercase
for (int i = 0; i < 26; i++) /* Simply store uppercase versions of the characters */
{
keyu[i] = toupper(key[i]);
}
// key of lowercase
for (int i = 0; i < 26; i++) /* Simply store lowercase versions of the characters */
{
keyl[i] = tolower(key[i]);
}
// create cyphertext
for (int i = 0; i < len; i++)
{
if (islower(pt[i]))
{
ct[i] = keyl[pt[i] - 97];
}
else if (isupper(pt[i]))
{
ct[i] = keyu[pt[i] - 65];
}
else
{
ct[i] = pt[i];
}
}
printf("cypher text: %s\n", ct);
return 0;
}
此重构代码的一些关键点是:
craig@Vera:~/C_Programs/Console/Substitution/bin/Release$ ./Substitution zyxwvytsrqponmlkjihgfedcba
plaintext: checkers
cypher text: xsvxpvih
craig@Vera:~/C_Programs/Console/Substitution/bin/Release$ ./Substitution zyxwvytsrqponmlkjihgfedcba
plaintext: xsvxpvih
cypher text: checkers
craig@Vera:~/C_Programs/Console/Substitution/bin/Release$ ./Substitution Hello there
Usage: ./substitution key
craig@Vera:~/C_Programs/Console/Substitution/bin/Release$
我绝没有诋毁“CS50”支持库和文件的意思。在学习中使用您认为合适的功能。但是,当您评估其他来源的代码时,您可能会看到字符数组定义和其他变量定义等项目更有可能采用这种常见格式。因此,您也希望能够适应以这种方式构建的代码。