reading and writing to a file with fstream

147 Views Asked by At
bool remove_vowels(const std::string& file_name) {

    std::fstream fs{ file_name , std::ios_base::in | std::ios_base::out };   
    if (!fs) { std::cout << "Error file not open"; return false; }

    char in{};

    while (fs >> in) {

        switch (tolower(in)) { 

        case 'a': case 'e': case 'i': case 'o': case 'u':
        {
            int64_t pos{ fs.tellg() }; 
            fs.seekp(pos - 1);         
            fs << ' ';                 
            fs.seekg(pos);
            
            break;
        }
        }
    }

    return true;
}

I try to solve one exercise from: Programming: Principles and Practice Using C++ Bjarne Stroustrup

  1. Write a program that removes all vowels from a file (“disemvowels”). For example, Once upon a time! becomes nc pn tm!. Surprisingly often, the result is still readable; try it on your friends.

The text file contain: "Once upon a time"

When i try this code inside the switch case:

int64_t pos { fs.tellg() }; // it get position one character forward
        fs.seekp(pos - 1);  // i set the write position to the the character         
        fs << ' ';          // then i replace the vowel to whitespace and increment one position

i get infinite loop that overwrite all the file with these characters "nc "

its only work for me this way:

int64_t pos{ fs.tellg() }; 
            fs.seekp(pos - 1);         
            fs << ' ';                 
            fs.seekg(pos);

Why it is necessary to set the position after fs << ' '; if its already increases it?

0

There are 0 best solutions below