整句操作麻烦

时间:2017-03-04 19:18:40

标签: c++ arrays string input data-manipulation

我正在制作一个猪拉丁语转换器,我可以让它操纵一个单词并需要它来转换整个句子,使每个单词输出为猪拉丁语,下面是我的代码:

#include <iostream>
#include <string>
#include <cstring>
#include <fstream>

using namespace std;

bool isVowel (char);
string rotate(string);
string plString(string);

int main()
{
string str;
cout <<"Enter a sentence: ";
getline (cin, str);
cout << endl;
cout << str <<" in pig latin - " << plString(str) << endl;

ifstream infile;
infile.open("input.txt");
infile >> str;
while(infile)
{
    cout << plString(str) << " ";
    infile >> str;
}

cout << endl;
}
bool isVowel (char ch)
{
switch (ch)
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
case 'Y':
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'y':
    return true;
default:
        return false;
}
}
string rotate(string str)
{
string::size_type len = str.length();
string str1;
str1 = str.substr(1, len - 1) + str[0];
return str1;
}
string plString(string str)
{
string::size_type len;
bool vowel;
string::size_type counter;
if (isVowel (str[0]))
    str = str + "way";
else
{
    str = str + "";
    str = rotate(str);
    len = str.length();
    vowel = false;
    for (counter = 1; counter < len - 1; counter++)
        if (isVowel (str[0]))
        {
            vowel = true;
            break;
        }
        else
            str = rotate(str);
    if(!vowel)
        str = str.substr(1,len) + "way";
    else
        str = str + "ay";
}
return str;
}

任何关于如何让它做完整句子的建议将不胜感激!

1 个答案:

答案 0 :(得分:0)

您需要将字符串拆分为单词(按空格分隔符拆分)。如果您在getline来电之后插入而不是" in pig latin - "行,这可能会有所帮助:

char delimiter = ' ';
string::size_type i = 0;
string::size_type j = str.find(delimiter);

while (j != string::npos) {
    string word = str.substr(i, j-i);
    std::cout << plString(word) << std::endl;
    i = ++j;
    j = str.find(delimiter, j);

    if (j == string::npos) {
        word = str.substr(i, s.length());
        std::cout << plString(word) << std::endl;
    }
 }