0

In my program one of the functions I want to create is going take an input file and replace every vowel with '3'. I've done something but it's not working obviously. I was hoping I could get some help with it:


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();
};
  • 4
    This is a one-line solution using `std::replace_if`. So are you ready for such a solution? – PaulMcKenzie Apr 03 '19 at 23:06
  • if(line.at(i) != 'a' || line.at(i) != 'e' || line.at(i) != 'i' || line.at(i) != 'o' || line.at(i) != 'u') tht's always true by the way.. you should consider changing the || for & – Spinkoo Apr 03 '19 at 23:25
  • Also you can make it check for Capital letter vowels: `if( std::toupper(line.at(i)) != 'A' )` or the opposite way with `std::tolower`. – Raindrop7 Apr 03 '19 at 23:26

1 Answers1

2

There are several issues with your program.


First, your boolean logic is faulty. You have this:

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

When it should be the following:

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

However we can make this code "neater" by using strchr to do a simple search:

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

Second, this statement:

while(!dataIn.eof())

This should not be done. Please read this for more information.


Third, you can write most of that function using 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;
    }
};
PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45