首页 > 解决方案 > 带有 std:out_of_range 问题的简单密码 (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;
}

谢谢//全部

标签: c++

解决方案


看起来latSortedlatUnstorted是不同的长度。

char cryptChar = latUnstorted.at(i);

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


推荐阅读