gpt4 book ai didi

c++ - 为什么我会收到内存错误?

转载 作者:行者123 更新时间:2023-11-28 02:51:09 25 4
gpt4 key购买 nike

当我运行这个 C++ 程序并执行它的函数时,我得到了这个内存错误,不知道为什么

TESTER 12345.exe 中 0x769DC41F 处的未处理异常:Microsoft C++ 异常:内存位置 0x0042F558 处的 std::invalid_argument。

我在 Visual Studio 2013 上运行它。

#include <iostream>
#include <string>
#include <algorithm>
#include <iomanip>
#include <cmath>

using namespace std;

string encrypt(string, int);
string decrypt(string source, int key);
int main(int argc, char *argv[])
{
string Source;
string userInput;
string keyString;

int Key;
int locationSpace = 0;
int locationOfFirstKeyIndex = 0;

int choice;

/*locationSpace = userInput.find(" ");

keyString = userInput.substr(locationOfFirstKeyIndex, locationSpace);
Source = userInput.substr(locationSpace + 1);

Key = stoi(keyString);*/

cout << "To encode a message type 1, to decode a message type 2: ";
cin >> choice;

if (choice == 1)
{
cin.ignore();
cout << "Enter a message to decode: ";
getline(cin, Source);
locationSpace = userInput.find(" ");

keyString = userInput.substr(locationOfFirstKeyIndex, locationSpace);
Key = stoi(keyString);
Source = userInput.substr(locationSpace + 1);

encrypt(Source, Key);
cout << "Encrypted: " << encrypt(Source, Key) << endl;
}
else if (choice == 2)
{
cin.ignore();
cout << "Enter the message To decode: ";
getline(cin, userInput);
locationSpace = userInput.find(" ");

keyString = userInput.substr(locationOfFirstKeyIndex, locationSpace);
Key = stoi(keyString);
Source = userInput.substr(locationSpace + 1);


decrypt(Source, Key);
cout << "Decrypted: " << decrypt(Source, Key) << endl;
}
else
{

cout << "Invalid Input";
}

system("pause");
}

string encrypt(string source, int key)
{
string Crypted = source;

for (int Current = 0; Current < source.length(); Current++)
Crypted[Current] = ((Crypted[Current] + key) - 32) % 95 + 32;
return Crypted;
}

string decrypt(string source, int key)
{
string Crypted = source;

for (int Current = 0; Current < source.length(); Current++)
Crypted[Current] = ((Crypted[Current] - key) - 32 + 3 * 95) % 95 + 32;
return Crypted;
}

最佳答案

请引用以下链接了解这一点:

http://en.cppreference.com/w/cpp/string/basic_string/stol

stoi 方法在无法执行任何转换时抛出 *std::invalid_argument* 异常。您可能希望在将其传递给 stoi() 之前进行打印,并验证字符串是否有效。

std::cout<<keyString<<std::endl;

关于c++ - 为什么我会收到内存错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23024218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com