#include <iostream>
#include <string>
using namespace std;
string cardsShuffle(string orig_seq){
string choice;
int random = 0;
string shuffled_seq;
int orig_len = orig_seq.length();
while(orig_len > shuffled_seq.length()){
random = rand() % orig_seq.length();
while(random % 2 != 0){
random = rand() % orig_seq.length();
}
choice = orig_seq.substr(random,2);
orig_seq.erase(random,random 2);
shuffled_seq = shuffled_seq choice;
}
return shuffled_seq;
}
int main()
{
string orig_seq;
cout << "Enter orig_seq: \n";
cin >> orig_seq;
cout << cardsShuffle(orig_seq);
return 0;
}
This works perfectly until you try it with 10 characters then nothing is ever returned and the program just exist normally after going through the function as it normally does, except I can't figure out why it just decides it's done
CodePudding user response:
I don't get a normal exit, I get "Floating point exception(core dumped)".
The erase
function does not have the parameters you think it does - like substr
, the second is the length, not the "one past the end" index.
(std::string
has a peculiar interface, as it was created long before the standard collections were added.)
So you remove random 2
characters, and the longer the string, the greater the chance that you end up erasing too many characters, and that will lead to undefined behaviour.
Change that line to
orig_seq.erase(random, 2);