c++程序查找和替换文件中的字符串

C++ program to find and replace a string in file

本文关键字:字符串 文件 替换 程序 查找 c++      更新时间:2023-10-16

这是一个初学者的问题。我试图在文本文件中找到一个字符串,并将其替换回相同的文件。下面的代码可以很好地将文件的内容收集到缓冲区中并替换字符串。但是,当我试图保持数据回到同一个文件,它是充满了一些垃圾字符。请让我知道我做错了什么?

#include <iostream>
#include <fstream>
using namespace std;
const char *fileName = "Test.dat";
int main () {
// This is where we'll put the stuff we read from file
char buffer[ 100 ];

ifstream finout(fileName, ios_base::in | ios_base::out | ios_base::binary);
if(!finout.is_open())
{
    cout << "Can not open file " << endl;
    return(1);
}
while (finout.getline(buffer, sizeof(buffer))
{
    string g( buffer );
    string search = "am";
    string replace = "was";
    long j;
    if ( (j = g.find(str2)) != string::npos)
    {    
        g.replace(g.find(str2), str2.length(), "str");
        finout.write((char *) &g, sizeof(g)); //This won't work 
    }
cout << g << "n";
finout.close();
return 0;
}

我的Test.dat文件包含以下信息:

Hello, How are you?
I am fine.
  • 当你作为文本文件读写时,不要通过ios_base::binary
  • 打开它
  • 你把finout.close();放在你的读取循环中,所以它只工作一行。
  • 当你以文本形式读写文件时,使用文本流方法和操作符。

您正在尝试使用sizeof()操作符读取字符串的大小。

这不起作用,因为它是一个关键字,它给了你对象或类型的非动态大小。

您应该使用g.size()来访问字符串的大小!

但是首先,你可以处理流来处理你的bug:

finout << g;

就可以了。

首先,你想读和写一个文件,所以使用fstream而不是ifstream。其次,您有一个文本文件,所以不要使用ios_base::binary第三(char*) &g其中g是std::string不起作用,使用g.c_str()代替。(只写finout & lt; & lt;g;

现在你可以开始考虑实现了…