这个猪拉丁节目怎么了

What is wrong with this Pig Latin program?

本文关键字:节目 怎么了 丁节目      更新时间:2023-10-16

它应该做什么

我的piglatin程序应该从用户输入中获取一个短语并将其输出为piglatin。基本上,它会把"hello"这样的单词变成"ellohay"。


我的问题

当我输入hello my man时输出是ellohay y man an may当我只输入hello my时输出是ellohay y may。正如你所看到的,在成功翻译了第一个单词之后,它在翻译第二个单词时遇到了困难。它在ymay之后放置了一个空间,我无法弄清楚为什么这种情况一直发生。当我输入两个以上的单词时,输出就更奇怪了,如上所示。我想要发生的是,当我输入hello my man时,它输出ellohay ymay anmay。代码如下。谢谢!


#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
void phrase_Parser(string); // Goes through phrase and looks for ' ' to then pass to pigLatin_Translator()
void pigLatin_Translator(string);
int main()
{
    string phrase; //used for user word or phrase to be translated to piglatin
    cout << "Enter any word: ";
    getline(cin, phrase); 
    phrase_Parser(phrase);
    return 0;
}
void phrase_Parser(string phrase) {
    int startCount = 0;
    for (int i = 0; i < phrase.length(); i++) {
        if (phrase[i] == ' ') {
            string word = phrase.substr(startCount, i);
            startCount = (i + 1); // decides where to start the word next time it is ran through
            pigLatin_Translator(word); // runs word through translator
        }
    }
}
void pigLatin_Translator(string word) {
    string partOne;
    string partTwo;
    for (int x = 0; x < word.length(); x++) {
        if (word[0] == 'q' && word[1] == 'u') {
            cout << word.substr(2, word.length()) << word.substr(0, 2) << "ay ";
            break;
        }
         else if ((word[x] == 'a') || (word[x] == 'e') || (word[x] == 'i') || (word[x] == 'o') || (word[x] == 'u') || (word[x] == 'y')) {
            partOne = word.substr(x, word.length()); //from first vowel to end of word
            partTwo = word.substr(0, x); // from first letter to first vowel, not including the vowel
            cout << partOne << partTwo << "ay "; // adding "ay" to the end of the word
            break;  
        }
    }
}

您的问题在string word = phrase.substr(startCount, i);

您使用substr不正确。substr的第二个参数是希望提取的子字符串的长度。将i替换为i-startCount,您应该可以很好地使用。

或者,搜索更好的分割字符串的方法。有许多选项比手动操作要简单得多。