I am working on Caesar's cipher for an online course and I have a problem with the original value being in the final output, and I cannot seem to get rid of it. My suspicion is that it is due to
strcpy(str1, &final_val);
strcat(str2, str1);
being called in a wrong way, so when I run
make test && ./test 1
This provides my program with the argument 1
and provides the key to shift the letters and encode the message. I expect to see
plaintext: asd
ciphertext: bcd
Instead I get
plaintext: asd
ciphertext: bacbdc
If you want to try out the code, you will need to do it inside of this sanbox , because it has the required CS50 library.
Code
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
bool input_valid(int count, string arg);
bool in_alphabet(int count, string arg);
int main(int argc, string argv[]) {
int key;
int ascii_val;
char final_val;
string string;
char str1[80];
char str2[80];
// check input again if validation fails
if (!input_valid(argc, argv[1])) {
printf("Invalid input!\nUSAGE: ./caesar key\n");
return 1;
}
string = get_string("plaintext: ");
// get integer from string input
key = strtol(argv[1], NULL, 10);
for (int i = 0; i < strlen(string); i++) {
ascii_val = (int)string[i];
bool valid_lower_case = (ascii_val + key) >= 97 && (ascii_val + key) <= 122;
bool valid_upper_case = (ascii_val + key) >= 65 && (ascii_val + key) <= 90;
// check if value is a letter
if (isalpha(string[i])) {
// check if value is in the valid alphabet range
if (valid_lower_case || valid_upper_case) {
final_val = ascii_val + key;
} else {
// for lowercase: wrap around if the letter passes 'z'
final_val = 97 + (key - (122 - (ascii_val - 1)));
}
} else {
final_val = ascii_val;
}
strcpy(str1, &final_val);
strcat(str2, str1);
}
for (int i = 0; i < 5; i++) {
printf("%i\n", str2[i]);
}
printf("ciphertext: %s\n", str2);
}
bool input_valid(int count, string arg) {
// input has more args than just the file name
// input is an integer
return count > 1 && isdigit(arg[0]);
}
strcpy(str1, &final_val);
is undefined behavior. strcpy
expects both parameters to be pointers to null-terminated strings. However, since arrays decay to pointers when passed to functions, strcpy
doesn't know the difference between a pointer to an array of characters and the address of a single char
variable.
It will try to copy memory beginning at &final_val
into str1
, only stopping when it encounters a null terminator elsewhere in your process' memory, if there is one. To copy a single character to a string, just use str[x] = ch
and str[x + 1] = '\\0'
.
Replaced strcopy()
and strcat()
. Got it to work by appending to str2
like this:
str2[i] = final_val;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.