I am trying to encrypt() and decrypt() strings in the parentheses using this program, but it keeps encrypting and decrypting the closing parentheses and the words after.
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);
}
The decrypt code is similar to encrypt just reversed.
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:
How do I make it only encrypt/decrypt the words in the parentheses?
encrypt(textToEncrypt);
should be immediately after *closingParenthesis = '\0'
(inside the innermost if
).
input + 8
should be input + 7
. The fact that you used 7
on the previous line should have been a tip! Maybe you should avoid using "magic numbers" and derive those constants...