簡體   English   中英

替換文本文件中的元音

[英]Replace vowels in a text file

在我的程序中,我要創建的功能之一是獲取一個輸入文件,並將每個元音都替換為“ 3”。 我做了一些事情,但是顯然沒有用。 我希望可以得到一些幫助:

void replaceVowels(ifstream &dataIn, string outputFile) { string line; ofstream dataOut; dataOut.open(outputFile.c_str()); while(!dataIn.eof()) { getline(dataIn, line); for (int i = 0; i < line.length(); i++) { if(line.at(i) != 'a' || line.at(i) != 'e' || line.at(i) != 'i' || line.at(i) != 'o' || line.at(i) != 'u') { dataOut << line.at(i); } else { line.at(i) = '3'; dataOut << line.at(i); } dataOut << endl; } } dataOut.close(); };

您的程序存在幾個問題。


首先,您的布爾邏輯是錯誤的。 你有這個:

if(line.at(i) != 'a' || line.at(i) != 'e' || line.at(i) != 'i' 
                     || line.at(i) != 'o' || line.at(i) != 'u')

什么時候應該是以下情況:

if(line.at(i) != 'a' && line.at(i) != 'e' && line.at(i) != 'i' 
                     && line.at(i) != 'o' && line.at(i) != 'u')

但是,通過使用strchr進行簡單的搜索,可以使此代碼“更整潔”:

static const char *vowels="aAeEiIoOuU"
//...
bool isVowel = strchr(vowels, line.at(i)); // true if vowel, false otherwise

二,此語句:

while(!dataIn.eof())

不應這樣做。 請閱讀此以獲取更多信息。


第三,您可以使用std :: replace_if編寫大部分功能:

#include <cstring>
#include <algorithm>
//...
void replaceVowels(ifstream &dataIn, string outputFile)
{
    string line;
    static const char *vowels = "aAeEiIoOuU";
    ofstream dataOut;
    dataOut.open(outputFile.c_str());
    while(getline(dataIn, line))
    {
       std::replace_if(line.begin(), line.end(), 
                       [&](char ch) { return strchr(vowels, ch); }, '3');
       dataOut << line << endl;
    }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM