Question
Help to fix this please. This is a vigenere cipher implemented in C++. It gives me an error saying terninate called after throwing an instance
Help to fix this please. This is a vigenere cipher implemented in C++.
It gives me an error saying terninate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc
#include
#include
#include
using namespace std;
string expandKey(string plainText, string key)
{
int msgLen = plainText.size();
int keyLen = key.size();
for (int i = 0; ; i++)
{
if (msgLen == i)
i = 0;
if (keyLen == msgLen)
break;
key.push_back(key[i]);
}
return key;
}
string encrypt(string plainText, string key)
{
string cipherText;
int len = plainText.size();
for (int i = 0; i < len; i++)
{
int letter = ((plainText[i] + key[i]) % 26) + 'A';
cipherText.push_back(letter);
}
return cipherText;
}
string removeSpaces(string msg)
{
int len = msg.size();
for (int i = 0; i < len; i++)
{
if(msg[i] == ' ')
msg.erase(i, 1);
}
return msg;
}
int main()
{
string plainText;
string key = "SMITH";
cout << "Please enter the message to be encrypted: ";
getline(cin,plainText);
plainText = removeSpaces(plainText);
string newKey = expandKey(plainText, key);
string cipherText = encrypt(plainText, newKey);
cout << "Encrypted Message: " << cipherText << " ";
return 0;
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started