首页 > 解决方案 > 错误处理 C++:程序永远不会停止

问题描述

我刚刚开始使用 C++,所以请原谅我的误解。

我正在制作一个程序,其中下一个辅音被添加到每个辅音上。

例如,如果输入为joy,则结果为jkoyz。

因为 k 出现在 j 之后,所以它被插入到 j 之后,o 是元音,所以在 o 之后没有插入任何东西,而 z 在 y 之后插入,因为 z 在字母表中 y 之后。

#include <iostream>
#include <string>
#include <typeinfo>

using namespace std;

int main ()
{

    string str = "joy";

    string constant = "bcdfghjklmnpqrstvwxyzz";

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

        if (constant.find(str[i]) != string::npos) {

            int index = constant.find(str[i]);

            char closestConstant = constant[index + 1];           
            char *closestConstantPointer = &closestConstant;

            str.insert(0, closestConstantPointer);

        }
    }
}

问题出在str.insert(0, closestConstant);一线。有什么指导吗?

标签: c++pointerserror-handling

解决方案


当你添加一个辅音,然后i只增加一次,你的光标最终会落在新的辅音上,所以你总是在添加新的辅音。像这样:

joy
jkoy
jkloy
jklmoy

等等。

i解决方案是在添加辅音时递增。for保留循环内的增量;你只需要在命令i之后再次增加。str.insert(...)


推荐阅读