0
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;
}

我尝试解决一个练习:编程:使用 C++ 的原则和实践 Bjarne Stroustrup

  1. 编写一个程序,从文件中删除所有元音(“disemvowels”)。例如,从前!变成 nc pn tm!。令人惊讶的是,结果仍然是可读的。在你的朋友身上试试。

文本文件包含:“从前”

当我在开关盒内尝试此代码时:

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

我得到无限循环,用这些字符“nc”覆盖所有文件

它只对我有用:

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

fs << ' '; 如果位置已经增加,为什么还要设置位置?

4

0 回答 0