c++ - Pig Latin、for循环、字符串问题

标签 c++

当我键入 ask 两次时,我没有返回 askyay askyay,而是返回 ask askyay

当我输入 dog 两次时,我得到的不是 ogday ogday,而是 og dogday

我不确定我做错了什么。

#include <iostream>
#include <string>
#include <cctype>
#include <sstream>

using namespace std;

int main()
{

    string vowels = "aeiou";
    string new_word;
    string pig_message;
    string message;
    getline(cin, message);

    for (unsigned int i = 0; i <= vowels.length(); i++)
    {
        if (message[0] == vowels[i])
        {
            new_word = message + "yay ";
            cout << new_word;
        }
        else if (!message[0] == vowels[i])
        {
            pig_message = message.substr(1) + message[0] + "ay";
            cout << pig_message;
        }
    }
    system("pause");
    return 0;
}

最佳答案

用值替换变量并逐步执行代码。结果是预期的,因为您没有拆分单词然后附加“yay”或“ay”

new_word = message + "yay ";

将结果变成

new_word  = "ask ask" + "yay";

pig_message = message.substr(1) + message[0] + "ay";

将结果变成

pig_message  = "og dog" + "d" + "ay";

关于c++ - Pig Latin、for循环、字符串问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40519387/

相关文章:

java - 如何将C++运算符转换为Java

c# - 在 .NET 中独立运行 C++ 库

c++ - 如何将一串十六进制值转换为字符串?

c++ - 在 vector 循环中使用 int 而不是 size_t 可以吗?

c++ - "cannot convert ' 这个从 'const hand' 到 'hand &' 的指针是什么意思? (C++)

c++ - 将 char * 转换为 uint16 和 uint32

c++ - 结合 if constexpr() 与非 const 条件

c++ - 仅当从我的程序打开 CMD 时出现奇怪的 CMD 错误

c++ - 使用 boost 所有 linux 发行版编译 C++

c++ - 为什么不能将 C++11 大括号初始化与宏一起使用?