加密字符串但接收到无限循环

问题描述 投票:0回答:2

问题:

我正在尝试使用单个规则对std::string密码进行加密:

  • 在元音之前和之后添加“ 0”

使得bAnanASplit变为b0A0n0a0n0A0Spl0i0t。但是,我陷入了无限循环。

这里是代码:

    const std::string VOWELS = "AEIOUaeiou";
    std::string pass = "bAnanASplit";

    //Add zeroes before and after vowels
    for (int i = 0; i < pass.length(); ++i)
    {
        i = pass.find_first_of(VOWELS, i);
        std::cout << pass << "\n";
        if(i != std::string::npos)
        {
            std::cout << pass[i] << ": " << i << "\n";
            pass.insert(pass.begin() + i++, '0');
            pass.insert(pass.begin() + ++i, '0');
        }
    }

...结果:

bAnanASplit
A: 1
b0A0nanASplit
a: 5
b0A0n0a0nASplit
A: 9
b0A0n0a0n0A0Split
i: 15
b0A0n0a0n0A0Spl0i0t
b0A0n0a0n0A0Spl0i0t
A: 2
b00A00n0a0n0A0Spl0i0t
a: 8
b00A00n00a00n0A0Spl0i0t
A: 14
b00A00n00a00n00A00Spl0i0t
i: 22
b00A00n00a00n00A00Spl00i00t
b00A00n00a00n00A00Spl00i00t
...

有帮助吗?这肯定看起来很奇怪。

c++
2个回答
2
投票

永远,永远不要修改您要迭代的collectionl /容器!

为您省去了很多麻烦。

让我们从您的代码开始,并生成一个由0包围的元音的新字符串。

const std::string VOWELS = "AEIOUaeiou";
std::string pass = "bAnanASplit", replacement;

//Add zeroes before and after vowels
for (auto ch : pass)
{
    if(VOWELS.find(ch) != std::string::npos)
        replacement += '0' + ch + '0';
    else
        replacement += ch;
}

就在那里!


1
投票

如果i成为std :: string :: npos,您就不会退出循环。因此,i值到达最后i或i之后为0的位置时永远不会更改(这里我指的是spl i t的i)。在那种情况下,终止条件i < pass.length()成立,循环继续。但是再一次,最好不要在对其进行迭代时修改容器]

© www.soinside.com 2019 - 2024. All rights reserved.