gpt4 book ai didi

c++ - 替换并写入文件 C++

转载 作者:太空宇宙 更新时间:2023-11-04 13:52:36 27 4
gpt4 key购买 nike

我想编写代码来查找文件中的单词并替换单词。我打开文件,接下来我找到单词。我有替换词的问题。

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
string contain_of_file,a="car";
string::size_type position;
ifstream NewFile;

NewFile.open("plik1.txt");
while(NewFile.good())
{
getline(NewFile, contain_of_file);

position=contain_of_file.find("Zuzia");
if(position!=string::npos)
{
NewFile<<contain_of_file.replace(position,5, a );

}
}
NewFile.close();

cin.get();
return 0;
}

如何改进我的代码?

最佳答案

  1. 丢失using namespace std;

  2. 不要在需要之前声明变量;

  3. 我认为您要查找的英文单词是content -- 但我不是以英语为母语的人;

  4. getline 已经在 bool 上下文中返回 NewFile.good()

  5. 无需显式关闭NewFile

  6. 我会更改 NewFile 变量的大小写;

  7. 我认为您不能写入 ifstream,您应该管理如何替换文件的内容...

    <

我的版本是这样的:

#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>

int main() {
std::rename("plik1.txt", "plik1.txt~");

std::ifstream old_file("plik1.txt~");
std::ofstream new_file("plik1.txt");

for( std::string contents_of_file; std::getline(old_file, contents_of_file); ) {
std::string::size_type position = contents_of_file.find("Zuzia");
if( position != std::string::npos )
contents_of_file = contents_of_file.replace(position, 5, "car");
new_file << contents_of_file << '\n';
}

return 0;
}

关于c++ - 替换并写入文件 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22884711/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com