I'm having some issues with this problem set from CS50. What I'm trying to do is encrypt a message and it doesn't print the result.
This is what debug50 shows ciphertext to be before it reaches printf
This is my code, it's a mess
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
bool check_key(char k);
string cipher (char text[], int key);
char alphabet[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
int main(int argc, string argv[])
{
// Check the key
// Check if it's more or less than 1 command line argument
// If not print ERROR
if (argc != 2)
{
printf("ERROR!\n");
return 1;
}
// Check if it's non negative - <= 0
// Check if it's a valid int
// If not print "Usage: ./caesar key"
char k = *argv[1];
if (check_key(k) == 0 || k == '0')
{
printf("Usage: ./caesar key\n");
return 1;
}
// Turn key into and int
int key = atoi(argv[1]);
// Get text
string plaintext = "ABC"; //I used this as a placeholder for get_string("plaintext: ");
string ciphertext = cipher(plaintext, key);
// Print cipher
printf("ciphertext: %s\n", ciphertext);
}
bool check_key(char k)
{
return isdigit(k); // Doesn't take negative values
}
string cipher (char text[], int key)
{
// Take plaintext characters and change each character of it with the character key positions away
// Add the character from alphabet array to another chiper array
// Add cipher array to cipher string and return
int position = 0;
int text_position = 0;
int text_length = 0;
char ciphertext[strlen(text)];
do
{
if (alphabet[position] == text[text_position])
{
int key_position = position + key;
ciphertext[text_position] = alphabet[key_position];
position = 0;
text_position++;
}
else
{
position++;
}
}
while (text[text_position] != '\0');
string final_cipher = ciphertext;
return final_cipher;
}
I can't get it to print the ciphertext. I was wondering if the problem is because of the way I turned the array into a string, but I don't know any other way to do that besides using the overloaded operator.