Ultima modifica:
Ciao ragazzi, come da titolo, ho provato a fare una mia implementazione del cifrario di Cesare, per puro diletto. Il codice è funzionante e l'ho testato con compilatori diversi (anche se non serviva dato che la codifica ASCII è sempre la stessa) e sembra sempre terminare l'esecuzione correttamente. Potreste darci un' occhiata per verificare che non ci siano potenziali errori di cui non mi sono accorto? Ho utilizzato gli indici della tabella ASCII per effettuare la conversione dei caratteri: non si dovrebbe fare per evitare errori imprevisti, ma credo di aver adottato, nel codice, le contromisure adeguate affinché questo non accada. Posto di seguito il programma, grazie a chi mi risponderà!
C++:
/*
PROGRAM NAME: enCODER
SCOPE: The following program encrypts a text using the Caesar cipher
and the numerical values of the characters corresponding to the ASCII table.
DATE: 10/10/2023
AUTHOR: CrazyMonk
USAGE: Enter the cipher key (a number > 0) and a message (only letters) separated by a space.
*/
#include <iostream>
#include <string>
using namespace std;
const int INDEX_Z = 122;
const int INDEX_A = 97;
const int INDEX_SPACE = 32;
string convertToLowercase(string phrase);
string encryptPhrase(string phrase, int cipherKey);
void keyValidation(int &key, int min, int max);
int main() {
string phrase;
int cipherKey;
cout << "\nInsert a key between 1 and 25 to encrypt: ";
cin >> cipherKey;
keyValidation(cipherKey, 1, 25);
cout << "\n Enter the phrase to encrypt: ";
cin.ignore();
getline(cin, phrase);
string finalString = convertToLowercase(phrase);
cout << "\nThe encrypted phrase is:" << encryptPhrase(phrase, cipherKey) << endl;
return 0;
}
string convertToLowercase(string phrase){
int stringLength = phrase.length();
if (stringLength == 0){
return "ERROR! EMPTY STRING!";
}
for (int i = 0; i < stringLength; i++){
phrase[i] = tolower(phrase[i]);
}
return phrase;
}
string encryptPhrase(string phrase, int cipherKey){
int stringLength = phrase.length();
for (int i = 0; i < stringLength; i++){
if ((int(phrase[i]) + cipherKey) > INDEX_Z){ // Verifico che il carattere non fuoriesca dall'alfabeto
int finalCharIndex = (int)phrase[i] + cipherKey; //Calcolo quale sarebbe l'indice del carattere fuoriuscito
int difference = finalCharIndex - INDEX_Z; //Calcolo la differenza tra l'indice del carattere fuoriuscito e l'indice dell'ultima lettere dell'alfabeto minuscolo (z)
phrase[i] = (INDEX_A - 1) + difference; //Con la differenza precedentemente calcolata, torno all'inizio dell'alfabeto ed effettuo l'incremento rimanente
continue;
}
if (phrase[i] == INDEX_SPACE){
continue;
}
phrase[i] += cipherKey;
}
return phrase;
}
void keyValidation(int &key, int min, int max){
while (key < min || key > max){
cout << "ERROR. Insert a key between " << min << " and " << max << ": ";
cin >> key;
}
}