Encrypting a String in C++ - c++

I am in desperate need of help with my C++ program that is supposed to encrypt a string that the user inputs (source) and saves the encrypted string to another string (destination).
Before the string is encrypted, it runs through the lowerCaseString() function where it converts source to all lowercase. This function works perfectly fine.
Can you help my make my program properly display the encrypted message? I am new to C++.
My error:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::at: __n (which is 0) >= this->size() (which is 0)
#include <iostream>
#include <string>
#include <ostream>
#include <fstream>
#include <sstream>
#include <cctype>
#include <vector>
using namespace std;
string lowerCaseString(string &source);
bool substitution(string &source, string cipherKey, string &destination);
int main()
{
string source;
string cipherKey = "qwertyuiopasdfghjklzxcvbnm";
string destination;
ifstream inFile;
cout << "Please enter a string: " << endl;
cin >> source;
//eventually has to write to a file, but I want to get the cipher part working first
//cin >> cipherKey;
// inFile.open("C:/Users/ellio/OneDrive/Desktop/Freshman Semester 2/ECE 1080C/ECE Labs/otherlabfiles/small-file.txt"); /*make necessary change for
// file access path*/
// if (!inFile){
// cout << "Input file cannot be opened" << endl;
// return 0;
// }
// stringstream buffer;
// buffer << inFile.rdbuf();
// //change to file_string
// source = buffer.str();
lowerCaseString(source);
substitution(source, cipherKey, destination);
cout << destination << endl;
return 0;
}
//converts all letters that are upper case to lower case in source
string lowerCaseString(string &source)
{
unsigned i;
for(i = 0; i < source.size(); ++i)
{
if(isupper(source.at(i)))
{
source.at(i) = tolower(source.at(i));
}
}
return source;
}
//encrypts the source string based on the cipher key, then writes the encrypted string to string destination
bool substitution(string & source, string cipherKey, string &destination)
{
//the boolean function type is irrelevant to my error (I tried to run it with void type), I just have to return true or false if the
//string source is empty
//alphabet is used to compare to each value in source
string alphabet = "abcdefghijklmnopqrstuvwxyz";
unsigned i;
unsigned j;
//this for loop is probably unnecessary but I did it for the purpose of potential debugging
for(i = 0; i < source.size(); ++i)
{
destination.at(i) = source.at(i);
}
//if the string is empty
if(source.size() == 0)
{
return 0;
}
//if the string isn't empty
else
{
for(i = 0; i < source.size(); ++i)
{
for(j = 0; alphabet.at(j) == 'z'; ++j)
{
//if the current character in source is equal to a certain letter in the
//alphabet, write the corresponding value from the cipher key into destination
if(source.at(i) == alphabet.at(j))
{
destination.at(i) = cipherKey.at(j);
}
}
}
//changed this maybe change back
return 1;
}
}

Here is your substitution method working. The destination string was empty, causing the error :
bool substitution(string & source, string cipherKey, string &destination)
{
string alphabet = "abcdefghijklmnopqrstuvwxyz";
destination = source; // To make sure the size of destination is the same as source
if(source.size() == 0)
{
return false;
}
else
{
for(unsigned int i = 0; i < source.size(); ++i) // You can declare i and j in the loop if you want (in c++ not in c)
{
for(unsigned int j = 0; j < alphabet.size(); ++j) // way easier to use size instead of finding 'z'
{
if(source.at(i) == alphabet.at(j))
{
destination.at(i) = cipherKey.at(j);
}
}
}
return true;
}
}
Note that the character finding bit can be reduced to :
bool substitution(string & source, string cipherKey, string &destination)
{
string alphabet = "abcdefghijklmnopqrstuvwxyz";
destination = source; // To make sure the size of destination is the same as source
if(source.size() == 0)
return false;
else
{
for(unsigned int i = 0; i < source.size(); ++i)
destination.at(i) = cipherKey.at(alphabet.find(source.at(i)));
return true;
}
}

You were trying to access destination but it was empty. Try to avoid operating on particular indexes. It could be done like this:
void substituteCharacters(const std::string& source,
const std::string& cipherKey,
std::string& destination)
{
destination.reserve(source.size());//allocate memory once, so no allocation during push_backs
for(auto c : source)
destination.push_back(cipherKey[c-'a']);
}

Related

Making a Caesar Cypher, and it does not want to decipher the message

For a project, we have to make a Caesar Cipher using classes and save the encrypted message inside of a file so a user can decipher it with the program.
I input the message and it has no problem encrypting the message according to the displacement/key I input (since I gave an option for the user to place the displacement they please).
However, the problem lies in decripting the message. It seems to only decript the penultimate or last letter of what I inputted and it doesnt even bother to show the remaining characters of the message.
I have currently no idea why its acting the way it is, I figured I would have to change the message to take char variables instead of string, but that would mean rewriting a large chunk of the code, and at the moment, I would like to avoid having to rewrite the code from scratch. If there are no other options, then I guess I will have to rewrite the code.
Here is the code, (hope that helps and sorry if my message may seem messy, this is the first time I post anything here):
#include<iostream>
#include<string>
#include<fstream>
#include<ctime>
#include<cstdlib>
/* This is a program that will grab a message from the user and encrypt it, then decrypt it
It will also generate a random 8-digit character password used to access the encrypted file
It will also have the ability to allow the user to choose how many spaces the cipher will take into account */
using namespace std;
//Implement a set displacement and get displacement
class Cipherer
{
private:
int displacement;
string message;
//string decryptMessage;
public:
void setDisplacer(int key);
int getDisplacer()const;
void msgEncripter(string, int);
string getMessage()const;
void msgDecripter(string);
string getDecription()const;
};
void Cipherer::setDisplacer(int key)
{
displacement = key;
}
int Cipherer::getDisplacer()const
{
return displacement;
}
void Cipherer::msgEncripter(string msg, int key)
{
string encriptedMsg = msg;
//.size returns the number of elements
for (unsigned int i = 0; i < msg.size(); i++)
{
if (msg[i] == 32) //32 is the value in ASCII of the space character
{
continue;
}
else
{
if ((msg[i] + key) > 122)
{
int temp = (msg[i] + key) - 122;
encriptedMsg[i] = 96 + temp;
}
else if (msg[i] + key > 90 && msg[i] <= 96)
{
int temp = (msg[i] + key) - 90;
encriptedMsg[i] = 64 + temp;
}
else
{
encriptedMsg[i] += key;
}
}
}
message = encriptedMsg;
}
string Cipherer::getMessage()const
{
return message;
}
void Cipherer::msgDecripter(string msg)
{
string decriptedMsg;
for (unsigned int i = 0; i < msg.size(); i++)
{
if (msg[i] == 32)
{
continue;
}
else
{
if ((msg[i] - displacement) < 97 && (msg[i] - displacement) > 90)
{
decriptedMsg[i] = (msg[i] - displacement) + 26;
}
else if ((msg[i] - displacement) < 65)
{
decriptedMsg[i] = (msg[i] - displacement) + 26;
}
else
{
decriptedMsg = msg[i] - displacement;
}
}
}
message = decriptedMsg;
}
string Cipherer::getDecription()const
{
return message;
}
static const char PASSWORD_POOL[] =
"0123456789";
int poolSize = sizeof(PASSWORD_POOL) - 1;
char getRandChar()
{
return PASSWORD_POOL[rand() % poolSize];
}
int main()
{
srand(time(0));
string pass, input, msg;
int key;
Cipherer message;
ofstream outputFile;
ifstream inputFile;
outputFile.open("SecretMSG.txt");
cout << "Write a message: \n";
getline(cin, msg);
cout << "Choose the displacement of the message (0-25): ";
cin >> key;
message.setDisplacer(key);
message.msgEncripter(msg, key);
outputFile << msg;
outputFile.close();
for (int count = 0; count < 1; count++)
{
for (int i = 0; i <= 7; i++)
{
pass += getRandChar();
}
cout << pass << endl;
}
cout << "Input password " << pass << " ";
cin >> input;
if (input == pass)
{
//Make a local variable to read file
string encryptedMessage;
inputFile.open("SecretMSG.txt");
inputFile >> encryptedMessage;
inputFile.close();
cout << message.getMessage() << endl;
cout << "If you wish to decrypt the message, type in the password once again " << pass << ": ";
cin >> input;
if (input == pass)
{
message.msgDecripter(encryptedMessage);
cout << message.getDecription() << endl;
}
else
{
exit(EXIT_FAILURE);
}
}
else
{
exit(EXIT_FAILURE);
}
system("pause");
return 0;
}
In msgDecripter your string decriptedMsg creates a string with the size 0, so any decriptedMsg[i] = is undefined behavior.
In your msgEncripter you write string encriptedMsg = msg;, and because you create a copy of mgs the encriptedMsg has the same size.
So either you do string decriptedMsg = msg or string decriptedMsg = std::string(msg.size(), ' ');
But a more c++ like approach would be to use transform.
string encriptedMsg = msg;
std::transform(encriptedMsg.begin(), encriptedMsg.end(), encriptedMsg.begin(),
[](unsigned char c) -> unsigned char {
if( c == ' ') {
return c;
} else {
// ... your other encrypting logic ...
}
});
Or using msg as source and an empty string as target and utilize std::back_inserter.

accessing data within array of structure in C++

This is an assignment that required me to use ifstream to stream a CSV file. this csv file contains 52 state names and amount of different resources used by each state. for example:
Alabama,410.20,715.70,169.40,18.00,44.90,309.10,11.90,417.30,64.50,167.40,23.70,0.10,0.40,0.00
then I need to prompt the user to type the state name and the output is the percentage of resources used.
I created a struct containing a string type and an array to store the value of each state and created an array of struct to store multiple state's data, but I am not sure whether my code is right, and I want to know how to access other data, such as the data store in my double array, when the user input a state name.
here is my code:
struct statData
{
string statename;
double StatDataNumber[14];
}DataStruc[51];
int main()
{
ifstream indata;
string line;
statData State;
State.statename;
statData Consumption;
Consumption.StatDataNumber;
indata.open("Data2016.csv"); //opening file
if (indata.fail()) //fail safe
{
cout << "Fail to open file";
exit(1);
}
getline(indata, line); //skipping the first line of the csv file
int i;
int N = 0;
int NLoop;
int Loop = 0;
string InvertValueBefore;
double InvertValueAfter;
char comma;
while (indata.eof()) // before file reache the end
{
for (NLoop = 0; NLoop < 51; NLoop++) // struct array loop
{
{
getline(indata, DataStruc[Loop].statename, ',');// getting statename
for (i = 0; i <= 12; i++) // each group of data, except last
{
indata >> DataStruc[Loop].StatDataNumber[N] >> comma;// storing data in struct
N++;
}
getline(indata, InvertValueBefore); // store last value as string
InvertValueAfter = stoi(InvertValueBefore); // convert it into double
InvertValueAfter = DataStruc[Loop].StatDataNumber[N]; // store it in array of struct
}
Loop++;
}
}
ReadData();
return 0;
}
void ReadData (ifstream& indata , statData DataStruc[] )
{
int i;
string input;
bool stayinloop = true;
cout << "Enter a statename or 'q' to quit\n";
getline(cin, input);
while (stayinloop == true)
{
if (input == "Alabama")
DataStruc[i].statename == "Alabama";
DataStruc[i].StatDataNumber[]
}
}
this code is not finished. Please let me know if you spot any other error. Thank you!
Your code is fine. However, certain points:
1. You just need to get rid of certain variables which are not required.
2. The "eof" function is used to identify if the end of file is reached. For which, you need to use while (!indata.eof()).
3. The "ReadData" method should appear before the main function, however, if you want to have your functions after the main function then first you need to define your function declaration before the main function (i.e. before main function, you can put "void ReadData (ifstream& indata , statData DataStruc[]);"), afterwards you can define your function.
Below is a working version of your requirements.
#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
using namespace std;
struct statData
{
string statename;
double StatDataNumber[3];
}DataStruc[2];
void ReadData (ifstream& indata , statData DataStruc[])
{
string input;
bool stayinloop = true;
while (stayinloop)
{
cout << "\nEnter a statename or 'q' to quit\n";
getline(cin, input);
for (int i = 0 ; i < 2; i++)
{
if (input == DataStruc[i].statename)
{
for(int j = 0 ; j < 3; j++)
{
cout << DataStruc[i].StatDataNumber[j] << ',';
}
}
else if(input == "q")
{
stayinloop = false;
}
}
}
}
int main()
{
ifstream indata;
string tempData = "";
string line;
string InvertValueBefore = "";
double InvertValueAfter = 0.0;
char comma = ',';
indata.open("test.csv"); //opening file
if (indata.fail()) //fail safe
{
cout << "Fail to open file";
}
getline(indata, line); //skipping the first line of the csv file
while (!indata.eof()) // before file reach the end
{
for (int NLoop = 0; NLoop < 2; NLoop++) // struct array loop
{
{
getline(indata, DataStruc[NLoop].statename, comma);// getting statename
for (int i = 0; i < 2; i++) // each group of data, except last
{
getline(indata, tempData, comma);
DataStruc[NLoop].StatDataNumber[i] = atof(tempData.c_str());
}
getline(indata, InvertValueBefore); // store last value as string
InvertValueAfter = atof(InvertValueBefore.c_str()); // convert it into double
DataStruc[NLoop].StatDataNumber[2] = InvertValueAfter;
}
}
}
ReadData(indata, DataStruc);
return 0;
}

Shifting an array of structs C++

I am quite new to c++ programming and data structures and really need some help. I am working on an assignment where I have a text file with 100 lines and on each line there is an item, a status(for sale or wanted), and a price. I need to go through the text file and add lines to an array of structs and as I add lines I need to compare the new information with the previously submitted information. If there is a line that is wanted and has a price higher than a previously input item that is for sale then the item would be removed from the struct and the array of structs shifted.
The place that I am having trouble is in actually shifting all the structs once a line that satisfies the condition is found.
My issue is that when I try to shift the array of structs using the second for loop nothing happens and I just get null structs and nothing seems to move.
Please if you guys can offer any help it would be greatly appreciated.
Below is the code of the text file and my current code.
#include<iostream>
#include<fstream>
#include <string>
#include <algorithm>
#include <sstream>
using namespace std;
struct items
{
string type;
int status;
int price;
} itemArray [100];
int main(int argc, char *argv[]) {
int x = -1;
//int chickenCount = 0;
int counter = 0;
int itemsSold = 0;
int itemsRemoved = 0;
int itemsForSale = 0;
int itemsWanted = 0;
string itemType;
int itemStatus = 0;
int itemPrice = 0;
int match = 0;
ifstream myReadFile( "messageBoard.txt" ) ;
std::string line;
//char output[100];
if (myReadFile.is_open()) {
while (!myReadFile.eof()) {
getline(myReadFile,line); // Saves the line in STRING.
line.erase(std::remove(line.begin(), line.end(), ' '), line.end());
//cout<<line<<endl; // Prints our STRING.
x++;
std::string input = line;
std::istringstream ss(input);
std::string token;
while(std::getline(ss, token, ',')) {
counter++;
//std::cout << token << '\n';
if (counter>3){
counter =1;
}
//cout << x << endl;
if (counter == 1){
itemType = token;
//cout<< itemType<<endl;
}
if (counter == 2){
if (token == "forsale"){
itemStatus = 1;
//itemsForSale++;
}
if (token == "wanted"){
itemStatus = 0;
//itemsWanted++;
}
//cout<< itemStatus<<endl;
}
if (counter == 3){
itemPrice = atoi(token.c_str());
//cout<< itemPrice<<endl;
}
//cout<<"yo"<<endl;
}
if (x >= 0){
for (int i = 0; i<100;i++){
if (itemArray[i].type == itemType){
//cout<<itemType<<endl;
if(itemArray[i].status != itemStatus){
if (itemArray[i].status == 1){
if(itemPrice>=itemArray[i].price){
itemsSold++;
match =1;
//itemArray[i].type = "sold";
for (int j=i; j<100-1;j++){
//cout<<j<<endl;
itemArray[j].type = itemArray[j+1].type;
itemArray[j].status = itemArray[j+1].status;
itemArray[j].price = itemArray[j+1].price;
}
i =i-1;
break;
}
}
if (itemArray[i].status == 0){
if(itemArray[i].price>=itemPrice){
itemsSold++;
match = 1;
//itemArray[i].type = "sold";
for (int j=i; j<100-1;j++){
//cout<<j<<endl;
itemArray[j].type = itemArray[j+1].type;
itemArray[j].status = itemArray[j+1].status;
itemArray[j].price = itemArray[j+1].price;
}
i=i-1;
break;
}
}
}
}
}
}
if (counter == 3 && match == 0){
itemArray[(x)].type = itemType;
itemArray[(x)].status = itemStatus;
itemArray[(x)].price = itemPrice;
}
match = 0;
// cout << itemArray[x].type << " " << itemArray[x].status<<" "<<itemArray[x].price<<endl;
}
for(int i=0;i<100;i++){
cout<<itemArray[i].type<< " "<<itemArray[i].status<<" "<<itemArray[i].price<<endl;
}
//cout<<itemArray[1].price<<endl;
cout << itemsSold<<endl;
}
myReadFile.close();
return 0;
}
text file: https://drive.google.com/file/d/0B8O3izVcHJBzem0wMzA3VHoxNk0/view?usp=sharing
Thanks for the help
I see several issues in the code, but without being able to test it, I think the main problem is that you always insert new elements at position 'x' which correspond to the currently line read from the file, without taking into account any shift of elements done. You should insert the new element at the first empty slot (or just overwrite the old element instead of shifting everything).
An other issue is that you do not initialize the status and price in your array.
The best way would be to rewrite the code by using more standard C++ features, for example:
replace the items structure by a class with a constructor defining default values
use object copy (there is no need to copy a struct element by element)
use standard C++ containers like a list (see http://www.cplusplus.com/reference/list/list/) which has insert and erase methods

Returning string from a function causing formatting issues

It's supposed to look like this: http://i.imgur.com/gko501E.png
Instead it looks like this: http://i.imgur.com/ISwqyD8.png
When I take the code out of the function and use it in the main class it works properly. However once I put it in this function the formatting problems occur, it also isn't filtering like it's supposed to. This program is supposed to take user input, store it in a string, remove all non-alphabetical characters, capitalize the vowels, and then space it out based on user defined variables given in the command line. It's also supposed to accept files as input in the command line, such as: 'program 5 8 < file'.
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <cstdlib>
#include <fstream>
#include <sstream>
using namespace std;
//make vowels uppercase
string filter(string input)
{
size_t found = input.find_first_of("aeiou");
while (found != string::npos)
{
if (islower(input[found]))
{
input[found] = toupper(input[found]);
found = input.find_first_of("aeiou", found + 1);
}
}
//Make consonants lowercase
size_t foundLower = input.find_first_of("BCDFGHJKLMNPQRSTVWXYZ");
while (foundLower != string::npos)
{
if (isupper(input[foundLower]))
{
input[foundLower] = tolower(input[foundLower]);
foundLower = input.find_first_of("BCDFGHJKLMNPQRSTVWXYZ", foundLower + 1);
}
}
//remove punctuation
for (int i = 0, len = input.size(); i < len; i++)
{
if (!isalnum(input[i]))
{
input.erase(i--, 1);
len = input.size();
}
}
return input;
}
int main(int argc, char* argv[])
{
int wordSize;
int wordSizeCounter;
int wordCounter = 0;
int rowSize;
//char letter;
wordSize = atoi(argv[1]);
rowSize = atoi(argv[2]);
ifstream inFile;
inFile.open(argv[3]);//open the input file
stringstream strStream;
strStream << inFile.rdbuf();//read the file
string test = strStream.str();//str holds the content of the file
if (!inFile) test = cin.get() ; // Read first character
//Begin filter for files
while (!test.empty())
{
filter(test);
if (test.length() < wordSize) //make sure we don't go out-of-bounds
{
wordSize = test.length();
}
cout << test.substr(0, wordSize);
cout << " ";
if (test.length() >= wordSize) //again, make sure we don't go out-of-bounds
{
test = test.substr(wordSize);
}
else
{
test = " ";
}
wordCounter++;
if (wordCounter == rowSize)
{
cout << std::endl;
wordCounter = 0;
}
if(test.empty())
{
test = cin.get();
}
}
cout << endl;
return 0;
}

Write a string to file not equal to string that read from it

Phase 1
example 1: I have string text = "01100001" then I want write to file "a"
example 2: I have string text = "0110000101100010" So I want write to file "ab"
NOTE:I solved phase 1 and result of writing is true.
Phase 2
for example 1:
I want read the file and put it to temp.
So temp = "a" and i convert it to "01100001"
for example 2:
I want read the file and put it to temp.
So temp = "ab" and i convert it to "0110000101100010"
Question
in my code i have below input
string text ="00000110101011100010001011111110011011110101100101110101101111010111111110101011"
"00111011000011100011100000100010111110111110111001100001110001110000101001111010"
"00000101";
I did "phase 1" and I opened the file in a hex editor the writing is true.
But after doing "phase 2" temp != text. Why?
My code
#include <iostream>
#include <sstream>
#include <vector>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
class bitChar{
public:
unsigned char* c;
int shift_count;
string BITS;
bitChar()
{
shift_count = 0;
c = (unsigned char*)calloc(1, sizeof(char));
}
string readByBits(ifstream& inf)
{
string s ="";
while (inf)
{
string strInput;
getline(inf, strInput );
for (int i =0 ; i < strInput.size() ; i++)
{
s += getBits(strInput[i]);
}
}
return s;
}
void setBITS(string X)
{
BITS = X;
}
int insertBits(ofstream& outf)
{
int total = 0 ;
while(BITS.length())
{
if(BITS[0] == '1')
*c |= 1;
*c <<= 1;
++shift_count;
++total;
BITS.erase(0, 1);
if(shift_count == 7 )
{
if(BITS.size()>0)
{
if(BITS[0] == '1')
*c |= 1;
++total;
BITS.erase(0, 1);
}
writeBits(outf);
shift_count = 0;
free(c);
c = (unsigned char*)calloc(1, sizeof(char));
}
}
if(shift_count > 0)
{
*c <<= (7 - shift_count);
writeBits(outf);
free(c);
c = (unsigned char*)calloc(1, sizeof(char));
}
outf.close();
return total;
}
string getBits(unsigned char X)
{
stringstream itoa;
for(unsigned s = 7; s > 0 ; s--)
{
itoa << ((X >> s) & 1);
}
itoa << (X&1) ;
return itoa.str();
}
void writeBits(ofstream& outf)
{
outf << *c;
}
~bitChar()
{
if(c)
free(c);
}
};
int main()
{
ofstream outf("ssSample.dat",ios::binary);
string text ="00000110101011100010001011111110011011110101100101110101101111010111111110101011"
"00111011000011100011100000100010111110111110111001100001110001110000101001111010"
"00000101";
cout<< text<<endl;
//write to file
bitChar bchar;
bchar.setBITS(text);
bchar.insertBits(outf);
outf.close();
ifstream inf("ssSample.dat" ,ios::binary);
//READ FROM FILE
string temp=bchar.readByBits(inf);
cout << endl;
cout << temp << endl;
return 0;
}
You have a LF Line Feed character. This is the character that is getting omitted.
0000 1010
This may be unrelated, but Windows requires a CR and LF for a new line. This code may act differently in Windows vs. Unix.
Read one byte at a time.
string readByBits(ifstream& inf)
{
string s ="";
char buffer[1];
while (inf.read (buffer, 1))
{
// string strInput;
//getline(inf, strInput );
//for (int i =0 ; i < strInput.size() ; i++)
//{
s += getBits(*buffer);
//}
}
return s;
}
Program output:
000001101010111000100010111111100110111101011001011101011011110101111111101010110011101100001110001110000010001011111011111011100110000111000111000010100111101000000101
000001101010111000100010111111100110111101011001011101011011110101111111101010110011101100001110001110000010001011111011111011100110000111000111000010100111101000000101
One problem with your approach is that your text must be a multiple of 8 bits to work. Otherwise, even if everything is correct, that last character will be read from the file and converted to 8 binary digits in the string adding trailing zeros.
Two problems I quickly identified (but I assume there are more)
Your input is not a multiple of 8-bits
By using getLine you're reading until you meet a delimiting character and thus spoiling your result since you're not dealing with a text-based file