簡體   English   中英

C ++程序查找和替換文件中的字符串

[英]C++ program to find and replace a string in file

這是一個初學者的問題。 我正在嘗試在文本文件中找到一個字符串,並將其替換回同一文件。 以下代碼可以很好地將文件內容收集到緩沖區中並替換字符串。 但是,當我嘗試將數據保留回同一文件時,它充滿了一些垃圾字符。 請讓我知道我在做什么錯嗎?

#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()運算符讀取字符串的sizeof()

這是行不通的,因為它是一個關鍵字,它為您提供了對象或類型的非動態大小。

您應該使用g.size()訪問字符串大小!

但是首先,您可以處理流來處理您的錯誤:

finout << g;

會做的工作。

首先,您要同時讀取和寫入文件,因此請使用fstream而不是ifstream。 其次,您有一個文本文件,因此不要使用ios_base :: binary Third(char *)&g,其中g是std :: string不起作用,請改用g.c_str()。 (簡單地寫finout << g;

現在您可以開始考慮實現了...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM