Alle
Alle

Reputation: 13

Simple Cipher with std:out_of_range issue (C++)

I'm totally new to programming and heard that C++ or the Assembly Language is a good startning point for someone that want to understand what happens under the hood. I want to follow this follow through even though some of you might have other suggestions. I've been an active student for a week now and for my second challange my teacher asked us to write a cypher. Nothing fancy, but something that scrambled and unscrambled the string written by the user. So far I've tried to scramble them for starters since I deduce that if I'll solve that problem, the unscramling will be achieved through a similar process. I know there's plenty of snippets of code out there already, but I'm really intressted and want to learn through the trial and error method, based on my own assumptions.

I would appriciate it greatly if someone could point out why I get the message: "Terminate called after throwing an instance of 'std::out_of_range'

#include <iostream>
#include <string>

using namespace std;

string latSorted {"abcdefghijklmnopqrstuvwxyz ,."};
string latUnstorted {"-_qazwsxedcrfvtgbyhnujmikolp"};

int main() {

cout << "\n -----------------------------------------------" << endl;
cout << " Enter some text: ";
string usrText;

string* p_usrText; // Pointer Initialization
cin >> usrText; // User enter text
p_usrText = &usrText; // Memory allocation gets assigned to the pointer variable

cout << " You've entered " << *p_usrText << endl << endl;

for (size_t i=0; i < latSorted.length(); i++)
{
    char searchChar = latSorted.at(i);
    char cryptChar = latUnstorted.at(i);
    for(size_t j=0; j < usrText.length(); j++)
    {
        if(usrText.at(j) == searchChar)
        {
            *p_usrText = usrText.replace(usrText.begin(), usrText.end(), searchChar, cryptChar); // Memory allocation is still within range due to the pointer. Should not say "out of range".
        }
    }
}
cout << ' ' << usrText << endl;
cout << endl;
return 0;
}

Thx//Alle

Upvotes: 0

Views: 62

Answers (1)

meat
meat

Reputation: 619

It appears that latSorted and latUnstorted are different lengths.

char cryptChar = latUnstorted.at(i);

Would result in the exception for the last value of i.

Upvotes: 1

Related Questions