如何从fstream文本中删除某些字符
How to remove certain characters from an fstream text?
我正在进行一个练习,该练习需要从文件中删除所有元音后从文件中输出文本。例如,包含文本"计算理论"的文件应输出" 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;
}
相关文章:
- 正在从C++中的字符数组中删除字符
- 从字符串中删除字符
- 如果不是十六进制,则QT从qlineedit中删除字符
- 从长字符串中删除字符
- 从文件对象的当前位置删除字符
- C++ 删除字符**
- 从字符串中删除字符的第一个和最后一个实例
- 如何在C++中删除字符*数组
- 如何从C 中的字符串中删除字符
- 用“ strcpy”在2D数组中删除(字符)的一行(字符)时是否存在任何错误
- 删除字符并在字符串(C )的末端附加它们
- C++ 字符串,用于删除字符'b'并将字符'a'替换为两个'd'的构建函数
- 在字符串中的定界符之间删除字符
- 从 std::字符串中删除字符从 "(" 到 ")" 用擦除?
- 使用擦除和删除从字符串中删除字符
- C++ 如何删除字符中的双引号
- C++ 中的密码 |打印字符后删除字符
- C++在链表中插入和删除字符
- 字符串流的获取函数不删除字符
- 删除字符C++最后一次出现时字符数组的开头