从第一个单词中删除元音

时间:2014-03-09 20:42:21

标签: c++11

程序编译,运行和工作。

大问题:

它只适用于句子的第一个单词。

示例:

"欢迎来到丛林"结果" wlcm"而不是" wlcm t th jngl"。

小问题:

有" 1"在运行时出现在输入和输出之间。我怎么能摆脱它呢?我认为是这样的,但我并不积极:

{
    withVowel.erase(i, 1);
    length = int(withVowel.length());
}

整个代码:

#include <iostream>
#include <string>
using namespace std;


void removeVowel(string&);       // Removes vowels from input string.
string withVowel;                // Will be used to read user input. 

int main ()
{   

    const string SENTINEL = "0";        // Sentinel value. 

    // Request input string unless SENTINEL is entered.  

    cout << "Enter a word or series of words." << '\n';
    cout << "Or, enter " << SENTINEL << " to quit." << '\n' << endl;
    cin >> withVowel;

    // In case of SENTINEL:

    while (withVowel == SENTINEL)
    {
        cout << '\n' << "***" << endl;
        return 0;
    }

    // Run loop.

    removeVowel(withVowel);

    // Display the string without vowels.

    cout << "The word(s) entered reflecting only consonants: " << withVowel << endl;

    return 0;
}

    void removeVowel(string& withVowel)
    {
        int i = 0;
        int length = int(withVowel.length());
        while (i < length)
    {
        if (withVowel.at(i) == 'a' || 
            withVowel.at(i) == 'A' || 
            withVowel.at(i) == 'e' || 
            withVowel.at(i) == 'E' ||
            withVowel.at(i) == 'i' || 
            withVowel.at(i) == 'I' || 
            withVowel.at(i) == 'o' || 
            withVowel.at(i) == 'O' || 
            withVowel.at(i) == 'u' ||
            withVowel.at(i) == 'U')

            {
                withVowel.erase(i, 1);
                length = int(withVowel.length());
            }
            else i++; 
        }

    // Display the string without vowels.   

    cout << removeVowel << endl;

    } 

2 个答案:

答案 0 :(得分:1)

使用getline(cin, withVowel);代替cin >> withVowel;

同时将while替换为main()中的if。 并且不要忘记upvote并接受答案=)

答案 1 :(得分:0)

只有获得第一个单词的问题是你正在使用cin >> withVowel;,它会在遇到空白时立即停止读取输入。请尝试使用std::getine(cin, withVowel);

如果可能的话,我会避免在适当的位置操纵字符串,如果它们不是元音,只需将其复制到输出中。

std::remove_copy_if(withVowel.begin(), withVowel.end(), 
    [](char c) { return c == 'a' || c == 'A' || 
                        c == 'e' || c == 'E' || 
                        c == 'i' ...;});