【发布时间】:2019-10-13 15:34:39
【问题描述】:
我需要删除文件中所有出现的字符串。 我将文本作为字符串接收并删除所有出现的事件。 在我删除了所有出现后,我不知道如何将字符串保存回文件。
我尝试关闭文件并使用 ofstream 进行写入,但没有成功。
#include <iostream>
#include <fstream>
#include <string>
int main () {
std::string file_contents = "";
std::ifstream myfile ("text.txt");
char ch;
if (myfile.is_open())
{
// READ FILE CONTENTS AS STRING
while ( myfile >> std::noskipws >> ch)
{
file_contents += ch;
}
// DISPLAY STRING
std::cout << file_contents << '\n';
// GET WORD TO BE DELETED
std::string word;
std::cout << "Please enter word to be deleted: ";
std::cin >> word;
std::string::size_type found;
std::string new_text;
//DELETE WORD FROM STRING
bool ok=0;
do{
found = file_contents.find(word);
ok=1;
if (found!=std::string::npos)
{
std::cout << word << " found at: " << found << '\n';
file_contents.erase(found, word.length());
std::cout << file_contents << '\n';
}
else
ok==0;
new_text=file_contents;
}while(ok==1);
myfile.close();
}
else std::cout << "Unable to open file";
return 0;
}
【问题讨论】:
-
ifstream是输入文件流,不能往文件里放东西。为什么不关闭 ifstream,从检索到的内容中删除单词,然后使用ofstream打开同一个文件并写入所有内容? -
请出示minimal reproducible example,您说您尝试使用
ofstream但它不起作用,是什么原因不起作用?这个代码在哪里? -
我试过了,但没用。文件保持不变
-
旁注:请使用
true或false作为bool变量。 -
@user9888273 我添加了一个有效的答案。