简体   繁体   中英

std::out_of_range error accessing a std::string in C++

I am part of a team of three moderate-aptitude programmers, and we are currently attempting to write a program in C++ to embody our new encryption algorithm. However, we have encountered an error which indicates that we are surpassing the length of a string, at some point. I have tried debugging this, myself, but I have had no luck. It's in the jumble() function, though ...

Anyway, here's a paste of our sourcecode with a temporary main() function: http://pastebin.com/GvvYAsKg

It compiles fine, but upon running, we get the following error:

terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::substr Aborted

One of your problems is in this line:

for(int i = 0; i < ( inPT.length() + 1 ); i++)

This will mean you attempt to access inPT[inPT.length] which is one character beyond the end of the string. You want

for(int i = 0; i < inPT.length(); i++)

or possibly to be using a more idiomatic C++ construct like std::for_each so you can't make this kind of fencepost error. As noted in the comments, running this in a debugger would have pointed this out to you pretty quickly.

Presumably this piece of code

if(modCount >= inPT.length())
{
    modCount = 0;
}
int mod = inKey.at(modCount);         

is meant to read

if(modCount >= inKey.length())
{
    modCount = 0;
}
int mod = inKey.at(modCount);         

Your guard on an out of range access on inKey is using the wrong variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM