为什么字符串随机播放在字符串中的 10 个字符后停止工作?

Why does string shuffle stop working after 10 characters in the string?

#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;
}

这非常有效,直到您尝试使用 10 个字符,然后什么都没有返回,并且程序在像往常一样通过函数后正常存在,除了我不明白为什么它只是决定完成

我没有正常退出,我收到“浮点异常(核心已转储)”。

erase 函数没有您认为的参数 - 像 substr,第二个是长度,而不是“最后一个”索引。
std::string 有一个特殊的界面,因为它是在添加标准集合之前很久创建的。)
所以你删除了 random+2 个字符,字符串越长,你最终删除太多字符的可能性就越大,这将导致未定义的行为。

将该行更改为

orig_seq.erase(random, 2);