猪拉丁语,for循环,字符串问题

时间:2016-11-10 03:10:45

标签: 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;
}

1 个答案:

答案 0 :(得分:3)

用值代替变量并逐步执行代码。结果是预期的,因为你没有拆分单词然后附加“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";