c++ - 带有 std :out_of_range issue (C++) 的简单密码

标签 c++

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

如果有人能指出我收到消息的原因:“在抛出 '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;
}

谢谢//所有

最佳答案

看起来 latSortedlatUnstorted 的长度不同。

char cryptChar = latUnstorted.at(i);

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

关于c++ - 带有 std :out_of_range issue (C++) 的简单密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51052227/

相关文章:

c++ - c++ 一个函数返回两个值

c++ - 在 C++ 中定义数组大小

c++ - 矩阵乘法在 C++ 中不起作用

c++ - 检查A是否是B的子类?

c++ - 在设计时未考虑异常安全的方法/类中提供强有力的保证

c++ - LNK1169 "one or more multiply defined symbols found"在基本游戏中

c++ - 什么是 undefined reference /未解析的外部符号错误,我该如何解决?

c++ - 自定义 Vector2D 类中的浮点错误

c++ - MFC:动态 CEdit ctrl 没有应用与非动态 CEdit ctrl 相同的视觉样式

C++ 类继承和赋值运算符