Im currently working on a project that is supposed to take a key with 26 characters.This key basicaly makes a new alphabet so someone could cipher a word.
For example, if the user inputs the key
VCHPRZGJNTLSKFBDQWAXEUYMOIand the word"Hello", the console should answer with "jrssb".Currently, if I input the word "hello", the console prints out "MOAAB" which I don't understand why it does it. ```
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
string cipher_word( string key , string text){
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 i = 0 ;
int j = 0 ;
string cipher = text;
while(text[i] != '\0'){//iterates through every char in the string
while(j < 26){
char tmpKey;
char tmpAlphabet;
tmpKey = key[j];
tmpAlphabet = alphabet[j];
if(islower(text[i])){
tmpAlphabet = tolower(tmpAlphabet);
}//makes it so the loop can iterate through lowercase letters
if(text[i] == tmpAlphabet){
if(islower(cipher[i])){
cipher[i] = tolower(tmpKey);
}//is supposed to make the word lowercas if the user inputs a word in lowercase
cipher[i] = tmpKey;
}//ciphers the word
j++;
}
j = 0;
i++;
}
return cipher;
}
int main(int argc, string argv[])
{
string key = get_string("What is the key? ");
string text = get_string("what text do you want to cipher? ");
string cipher = cipher_word(key,text);
printf("%s\n",cipher);
}
I tried adding the following:
if(isupper(text[i])){
text[i] = tolower(text[i]);
}
It worked but it didn't take into account the uppercase and lowercase letters the user inputs in text. Please explain to me what's wrong with my code?
In reviewing your code and what was supposed to be the desired output, I took a step back to derive a more generic method of translating/ciphering text. First off, whenever I encounter a question arising for the online tutorials that involve the "CS50" functions, I usually opt to replace the "CS50 specific" functionality within this library set with more generic methods and functions, especially when it comes to string manipulation.
With that in mind, following is a refactored version of your translation function and data entry at the terminal.
Give that a go. Hopefully, that clarifies character matching and translation.
The key bits are:
With those bits of simplification, following was a test at the terminal for a couple of words.
Doing some bench testing, the function performed the desired character replacements to produce the ciphered text.