I'm working on learning C++ coming from python. I'm doing some projects to help me out understanding the language a bit more.
My code works I just want to know if there is anything that I can improve on it or best practices in C++, maybe something that I should have done differently.
// Ceaser Cipher implementation
#include <iostream>
#include <string>
char shiftF(char ch, int shift, const char type)
{
if (type == 'e')
{
return ch == 'z' || ch == 'Z' ? ch - 25 : ch + shift;
}
else if (type == 'd')
{
return ch == 'z' || ch == 'Z' ? ch - 25 : ch - shift;
}
}
std::string encode(std::string str, int shift, char type)
{
std::string tempMsg;
for (auto ch : str)
{
if (isalpha(ch))
{
tempMsg += shiftF(ch, shift, type);
}
else if (isspace(ch))
{
// There is probably a better way to do this.
tempMsg += " ";
}
else if (isalnum(ch))
{
continue;
}
}
return tempMsg;
}
int main(int argc, char *argv[])
{
int choice;
std::cout << "What do you want to do? 1.Encrypt, 2.Decrypt: ";
std::cin >> choice;
std::string result;
const char dec = 'd';
const char enc = 'e';
if (choice == 1)
{
int key;
std::cout << "Enter encryption shift: ";
std::cin >> key;
std::string msg;
std::cout << "Enter a message: ";
// This doesn't work for some reason?
// std::cin.clear();
// std::cin.sync();
std::cin.ignore();
std::getline(std::cin, msg);
result = encode(msg, key, enc);
}
else if (choice == 2)
{
int key;
std::cout << "Enter decryption shift: ";
std::cin >> key;
std::string msg;
std::cout << "Enter a message: ";
std::cin.ignore();
std::getline(std::cin, msg);
result = encode(msg, key, dec);
}
else
{
std::cout << "Wrong option, exiting!";
}
std::cout << "Message encoded: " << result;
}