如何从fstream文本中删除某些字符

How to remove certain characters from an fstream text?

本文关键字:删除 字符 文本 fstream      更新时间:2023-10-16

我正在进行一个练习,该练习需要从文件中删除所有元音后从文件中输出文本。例如,包含文本"计算理论"的文件应输出" thry f cmpttn"。

我尝试构建一个函数'removeVowel(ifSream&)',该函数从ifstream中读取数据并将其存储在字符串中,然后将所有非宽字符添加到新字符串中并返回该字符串。

bool isVowel(char ch){
switch (ch) {
case'a':
case'e':
case'i':
case'o':
case'u':
    return true;
}
return false;
}
string removeVowel(ifstream& line){

string ss;
string no_Vow;
while (getline(line, ss)) {
    for (int i = 0; i < ss.size(); i++) {
        if (!isVowel(ss[i]))
            no_Vow += ss[i];
    }
}
return no_Vow;
}
int main() {
string nahmen;
cout << "Enter file name";
cin >> nahmen;
ifstream fs{nahmen};
ofstream fso{ nahmen };
fso << "A quick brown fox jumped over the lazy dog";
string new_s;
new_s = removeVowel(fs);
cout << new_s;
}

我希望没有元音的字符串在控制台中输出,但是程序终止而不输出字符串。

您的原始代码将在阅读之前覆盖输入,因此没有数据可以处理。通常,您不想破坏文件的数据,但是如果这样做,则需要将新文件内容存储在某个地方。对于较小的文件,可以在内存中执行此操作。对于较大的文件,最好将存储在临时文件中,然后将临时文件移到原始输入中。

以下是使用STL完成任务的示例,从而减少了您必须写的逻辑数量。

#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <iterator>
namespace {
static bool isVowel(char const ch) {
    // '' is considered part of the search string, thus need to handle it separately
    return (std::strchr("aeiouAEIOU", ch) != nullptr) && (ch != '');
}
static void setOutputExceptions(std::ostream &os) {
    // Set exceptions on this we usually don't want to handle for output strings
    os.exceptions(std::ios_base::badbit | std::ios_base::eofbit | std::ios_base::failbit);
}
}  // close unnamed namespace
int main() {
    setOutputExceptions(std::cout);
    std::cout << "Enter file name: ";
    std::string nahmen;
    std::cin >> nahmen;
    if (!std::cin) throw std::runtime_error("Unable to read file name");
    std::string fileContent;
    {
        std::ifstream fs{nahmen};
        if (!fs) throw std::runtime_error("unable to open file " + nahmen);
        // we do not copy the vowels to fileContent to save space
        remove_copy_if(std::istreambuf_iterator<char>(fs), std::istreambuf_iterator<char>(),
                       back_inserter(fileContent),
                       isVowel);
    }  // close fs
    // we don't to have a input and output handle to the same file at the same time
    {
        std::ofstream fso;
        setOutputExceptions(fso);
        fso.open(nahmen);
        fso << fileContent;
    }  // close fso
    return EXIT_SUCCESS;
}