c++ - 错误处理C++ : Program never stops

标签 c++ pointers error-handling

我只是刚开始使用C++,所以请谅解。

我正在编写一个程序,其中将下一个辅音添加到每个辅音上。

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

因为k在j之后,因此它被插入j之后,所以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);行中。有指导吗?

最佳答案

添加辅音时,仅增加i一次,您的光标最终移到新的辅音上,因此您总是要添加新的辅音。像这样:

joy
jkoy
jkloy
jklmoy

等等。

解决的办法是每添加一个辅音就增加i。将增量保留在for循环内;您只需要在i命令之后立即再次增加str.insert(...)

关于c++ - 错误处理C++ : Program never stops,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51295361/

相关文章:

c++ - 创建临时 char* 并打印到它的正确方法是什么?

go - `Exit(1)` 到哪里,哪里返回错误?

c++ - _pin 是一个全局变量,但我仍然收到错误 : '_pin' was not declared in this scope

c++ - DistCC 和 CMake - 在运行 make 时在本地和分布式构建之间进行选择

c++ - 试图读取AIFF文件意外错误与指针位置等有关

c++ - 将元素插入 std::vector<void **(void*)>

c++ - Xlib 致命 IO 错误 : 11 (resource temporarily unavailable) caused by not using XCloseDisplay()

c++ - 如何测试断言?

python - 防止 input() 为字母字符以外的任何内容

java - Java中的LBYL与EAFP?