I am pretty new to C++ and programming in general, so I decided to make a cipher program that changes each letter to the letter 4 spaces after it. I know its not well written and can be much better, but what I mainly need help with is that it's not running. I spent a while fixing errors, and it finally compiled, but now when I run it and enter what word I want to encrypt, it says, "cipher.exe has stopped working." If anyone can please tell me why this is happening and/or anything else to improve my poor coding, please let me know.
#include <iostream>
#include <string>
#include <sstream>
#include <map>
usingnamespace std;
string cipher(string msg, map<string,int> letters, map<int,string> nums){ //The function to cipher the statement has the maps in the parameters so that they can be used outside of the main function.
stringstream ss;
string b2;
string ans[msg.length()]; //The list of characters(as strings) of the encrypted message.
string c;
for(int x = 0; x < msg.length(); x++){
char b = msg[x];
ss << b;
ss >> b2; //Converts the char b to a string b2
int d = letters[b2]; //d is the numerical value of b2
d+=4; //adds 4 to d to encrypt the message
if(d > 26){
c = nums[d-26];
}
else{
c = nums[d]; //c is set to the alphabetical value of d
}
ans[x] = c; //c is put into the list of charcters of the encrypted message
}
}
int main(){
map<string,int> letters; //A map of letters a-z with numeric values.
letters["a"] = 1;
letters["b"] = 2;
letters["c"] = 3;
letters["d"] = 4;
letters["e"] = 5;
letters["f"] = 6;
letters["g"] = 7;
letters["h"] = 8;
letters["i"] = 9;
letters["j"] = 10;
letters["k"] = 11;
letters["l"] = 12;
letters["m"] = 13;
letters["n"] = 14;
letters["o"] = 15;
letters["p"] = 16;
letters["q"] = 17;
letters["r"] = 18;
letters["s"] = 19;
letters["t"] = 20;
letters["u"] = 21;
letters["v"] = 22;
letters["w"] = 23;
letters["x"] = 24;
letters["y"] = 25;
letters["z"] = 26;
map<int,string> nums; //A map of numbers 1-26 with alphabetical values.
nums[1] = "a";
nums[2] = "b";
nums[3] = "c";
nums[4] = "d";
nums[5] = "e";
nums[6] = "f";
nums[7] = "g";
nums[8] = "h";
nums[9] = "i";
nums[10] = "j";
nums[11] = "k";
nums[12] = "l";
nums[13] = "m";
nums[14] = "n";
nums[15] = "o";
nums[16] = "p";
nums[17] = "q";
nums[18] = "r";
nums[19] = "s";
nums[20] = "t";
nums[21] = "u";
nums[22] = "v";
nums[23] = "w";
nums[24] = "x";
nums[25] = "y";
nums[26] = "z";
string msg;
cout << "What would you like to encrypt?" << endl;
cin >> msg; //what is being encrypted.
cipher(msg,letters,nums); //Calls the cipher function
}
string ans[msg.length()]; //The list of characters(as strings) of the encrypted message.
This is not legal in C++. You may have some compiler extension enabled that allows it, nevertheless in C++ the size of an array must be specified by a compile time constant. (And why do you want an array of strings here anyway?)
However, I imagine the cause of your memory corruption is promising to return a string in cipher and not actually doing so.