当我运行这个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;
}
答案 0 :(得分:1)
我假设您取消注释代码时会导致错误。让我们来看看错误(你应该是这样做的,使用你的调试器):
keyString = userInput.substr(locationOfFirstKeyIndex, locationSpace);
//userInput is a blank string, lOFKI == 0 and so does locationSpace
stoi(keyString); //keyString is invalid, empty string
在解析之前,您应该尝试获取用户输入...
答案 1 :(得分:1)
请参阅以下链接以了解此事:
http://en.cppreference.com/w/cpp/string/basic_string/stol
stoi 方法在无法执行转换时抛出* std :: invalid_argument *异常。您可能希望在将其传递到stoi()之前进行打印,并验证字符串是否有效。
std::cout<<keyString<<std::endl;