这个猪拉丁节目怎么了
What is wrong with this Pig Latin program?
它应该做什么
我的piglatin程序应该从用户输入中获取一个短语并将其输出为piglatin。基本上,它会把"hello"这样的单词变成"ellohay"。
我的问题
当我输入hello my man
时输出是ellohay y man an may
当我只输入hello my
时输出是ellohay y may
。正如你所看到的,在成功翻译了第一个单词之后,它在翻译第二个单词时遇到了困难。它在y
和may
之后放置了一个空间,我无法弄清楚为什么这种情况一直发生。当我输入两个以上的单词时,输出就更奇怪了,如上所示。我想要发生的是,当我输入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
,您应该可以很好地使用。
或者,搜索更好的分割字符串的方法。有许多选项比手动操作要简单得多。
相关文章:
- 不断收到相同的错误...怎么了?C++
- 编译器没有显示错误,但我没有得到任何输出.怎么了?
- qsort 不适用于我的 impl 中的浮点类型。怎么了?
- 在C++中表现不佳.怎么了?
- 我的程序怎么了?(C )
- 这里怎么了?单位转换器
- 错误:未定义对 .. 的引用.怎么了
- 我试图编写一个代码来查找一个单词是否是回文,但它不起作用。怎么了?
- 我在C++文件中的简单代码块上有 2 个错误。错误 C2059:语法错误:"?"。第二智能感知:预期表达式。怎么了?
- 我的代码怎么了?带有QT的原始输入API
- 使用 cin.get() 似乎没有读取我期望的字符。怎么了?
- 当其中一个字符串来自cin时,无法比较两个字符串.这里怎么了
- "5"怎么了?纸上一切都很好
- 我的cout怎么了
- C++:腹肌怎么了
- Qt OpenGL with Widgets:怎么了?
- 程序为某些条目提供了错误的输出!怎么了?
- 自动和复制构造函数:怎么了?
- 怎么了???只有七行
- 这个猪拉丁节目怎么了