Reputation: 57
Iam getting this memory error when i run this c++ program and execute its functions any ideas why
Unhandled exception at 0x769DC41F in TESTER 12345.exe: Microsoft C++ exception: std::invalid_argument at memory location 0x0042F558.
iam running this on 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;
}
Upvotes: 0
Views: 3363
Reputation: 5741
Please refer the following link to understand about this:
http://en.cppreference.com/w/cpp/string/basic_string/stol
stoi method throws the *std::invalid_argument* exception when no conversion could be performed. You may want to print before passing it into stoi(), and verify that whether string is valid or not.
std::cout<<keyString<<std::endl;
Upvotes: 1
Reputation: 8805
I am assuming the error is caused when you uncomment the code. Lets run through the error (you should be the one doing this, with your debugger) :
keyString = userInput.substr(locationOfFirstKeyIndex, locationSpace);
//userInput is a blank string, lOFKI == 0 and so does locationSpace
stoi(keyString); //keyString is invalid, empty string
You should try getting your user input before parsing it...
Upvotes: 1