具有std:out_of_range问​​题的简单密码(C ++)

时间:2018-06-26 22:35:07

标签: c++

我是编程的新手,听说C ++或汇编语言是想了解幕后情况的人的一个很好的起点。我想遵循此步骤,即使其中一些人可能还有其他建议。我已经是一个活跃的学生,已经有一个星期了,在第二次挑战中,我的老师要求我们写一个密码。没什么好看的,而是对用户编写的字符串进行了加密和解密的内容。到目前为止,我已经尝试过对初学者进行加扰,因为我推断出如果我能够解决该问题,那么可以通过类似的过程来实现加扰。我知道已经有很多代码片段,但是我真的很感兴趣,并且想根据自己的假设通过试错法学习。

如果有人指出我为什么收到消息,我会大加赞赏:“抛出'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

1 个答案:

答案 0 :(得分:1)

看来latSortedlatUnstorted的长度是不同的。

char cryptChar = latUnstorted.at(i);

将导致i的最后一个值异常。