【发布时间】:2023-03-05 12:46:01
【问题描述】:
我用 C 创建了一个程序。该程序是一个版本替换字符串。我已经使用 printf 语句仔细分析了程序。我的程序逻辑工作正常。但是我无法添加或连接字符串。
我没有得到 encryptKey 函数的输出。这是为什么?我之前在 JS 中编程,现在正在尝试 C。
这是我的代码:-
#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>
string encryptKey(string message);
//stores the cipher word for each alphabet
//used for encryption purposes
char cipher[26];
int main(int argc, string argv[])
{
//Exit the program if no key is added in commandline
if(!argv[1] || argc >= 3)
{
printf("Incorrect or missing command line arguments!\n");
return 1;
}
//checks if there are 26 characters in the decipher key
if(strlen(argv[1]) != 26)
{
printf("Need 26 characters to decipher the key\n");
return 1;
}
//check all the individual characters of the key
for(int i = 0; i < 26; i++)
{
//check if the characters are letters only
if(tolower(argv[1][i]) < 'a' && tolower(argv[1][i]) > 'z')
{
return 1;
printf("All characters should be letters!\n");
}
//checks if each letter exists once
//load the secret key to an array
cipher[i] = argv[1][i];
}
//Asks user for message
string message = get_string("plaintext:");
string secretMessage = encryptKey(message);
//outputs secret message
printf("ciphertext: %s\n", secretMessage);
}
//encrypt the message
string encryptKey(string message)
{
string output = "";
//loop through each alphabet
for(int i = 0; i < strlen(message); i++)
{
char lower = tolower(message[i]);
if(lower >= 'a' && lower <= 'z')
{
//small case starts from location 97
int tempLocation = lower - 97;
if(isupper(message[i]))
{
output += toupper(cipher[tempLocation]);
}
else if(islower(message[i]))
{
output += tolower(cipher[tempLocation]);
}
else
{
output += message[i];
}
}
}
return output;
}
我什至试过这个来加入字符串:- strcat(输出, toupper(cipher[tempLocation]));
我收到此错误:-
error: incompatible integer to pointer conversion passing 'int' to parameter of type 'const char *' [-Werror,-Wint-conversion]
strcat(output, toupper(cipher[tempLocation]));
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/string.h:130:70: note: passing argument to parameter '__src' here
extern char *strcat (char *__restrict __dest, const char *__restrict __src)
^
【问题讨论】:
-
output += toupper(cipher[tempLocation]);不是 string 附加在 C 中。那只是添加到指针output。 -
我尝试使用 strcat 但我得到了上面发布的错误
-
strcat(output, toupper(cipher[tempLocation]));失败,因为 1)cipher[tempLocation])不是 字符串 和 2)output指向的空间太小。 (string output = "";是 1 个字节的字符) -
您需要在循环中为每个字符调用 toupper,确保字符串以 null 结尾,然后将其传递给 strcat。一般来说,你不能通过反复试验来编程,你必须知道你在做什么。这包括在调用之前研究你调用的每个函数。
-
所有字符串处理问题的根源是 CS50。这是一门非常糟糕的课程,未能教授如何在 C 中正确使用字符串。我强烈建议您停止学习。