我正在尝试使用此程序对括号中的字符串进行加密()和解密(),但它不断加密和解密右括号及其后面的单词。
if (strncmp(input, "encrypt", 7) == 0) {
char *textToEncrypt = input + 8; // Skip "encrypt" and the space
if (*textToEncrypt == '(') {
textToEncrypt++; // Skip the opening parenthesis
char *closingParenthesis = strchr(textToEncrypt, ')');
if (closingParenthesis) {
*closingParenthesis = '\0'; // Terminate the string at the closing parenthesis
}
}
encrypt(textToEncrypt);
}
void encrypt(char text[]) {
char encryptedChar;
char array[1000] = "";
for (int i = 0; i < strlen(text); i++) {
encryptedChar = text[i] + 5;
//printf("\nThe ASCII Value of %c is %u\n", encryptedChar, (unsigned char)encryptedChar);
strncat(array, &encryptedChar, 1);
}
printf("%s\n", array);
memset(array, 0, sizeof array);
}
解密代码与加密类似,只是相反。
Result
Enter command: encrypt(hi)
mn.
Enter command: decrypt(mn)
hi$
Enter command: encrypt(hi
mn
Enter command: decrypt(mn
hi
Enter command: encrypt(hi)ghjkl
mn.lmopq
Enter command: decrypt(mn)ghjk
hi$bcef
Enter command:
如何使其只加密/解密括号中的单词?
encrypt(textToEncrypt);
应紧接在 *closingParenthesis = '\0'
之后(在最里面的 if
内)。
input + 8
应该是input + 7
。事实上,您在上一行中使用了 7
应该是一个提示!也许你应该避免使用“幻数”并导出这些常量......