gpt4 book ai didi

c++ - 用 fstream 在最后一行写

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

我试图替换文本文件中的字符串。类似于 replace() 函数。

代码如下:

#include <iostream>
#include <fstream>
#include <cstring>
Using namespace std;
int main()
{

fstream file("C:\\Users\\amir hossein\\Desktop\\Temp1\\test1.txt");

char *sub; sub = new char[20]; sub = "amir";
char *replace1; replace1 = new char[20]; replace1 = "reza";
char *buffer; buffer = new char[100];


int i, temp; streampos flag;
int c=0,mark;
bool flagforwrite=0;


if (file.is_open()){
while (!file.eof()) {
flag = file.tellg();
file.getline(buffer, 100); //We'll Search Sub inside of Buffer, if true, we'll replace it with Replace string
flagforwrite=0;
for (i=0;buffer[i];i++){
mark=i; c=0;
while (sub[c] && sub[c]== buffer[mark]){
c++; mark++;
}

if (!sub[c]){ //Make Changes in The Line
for (int j=i,count=0;count<strlen(replace1);j++,count++) buffer[j] = replace1[count]; //until here, we've replace1d the sub
flagforwrite=1;
}

}

if (flagforwrite){ //Write The line ( After Whole Changes In line have been made!!
file.seekp(flag);
file << buffer << "\n"; // ENDL here IS SUPER IMPORTANT!! IF you don't put it, I'll mess it up
if(file.bad()) cout << "Error\n";
}
}
}

else cout << "Error!!\n";
file.close();
delete[] sub;
delete[] replace1;
delete[] buffer;


return 0;
}

我想用“reza”替换“amir”。

我的文本文件包括 4 行:

Hi My name is amir and also my friend's name is amir too!
Hi My name is amir and also my friend's name is amir too!
Hi My name is amir and also my friend's name is amir too!
Hi My name is amir and also my friend's name is amir too!

当我运行程序时,我得到了这个。

Hi My name is reza and also my friend's name is reza too!
Hi My name is reza and also my friend's name is reza too!
Hi My name is reza and also my friend's name is reza too!
Hi My name is amir and also my friend's name is amir too!

最后一行有什么问题?

我认为问题出在这里:

if (flagforwrite){ 
file.seekp(flag);
file << buffer << "\n";
if(file.bad()) cout << "Error\n";
}

为什么旗帜总是指线?

我正在使用 GNU GCC 编译器。

最佳答案

我找到问题了!是eof()造成的!所以我没有使用 while(!file.eof()) 我使用了 while(file.getline(buffer,100))

我也将 file.tellg() 移动到末尾,并定义了这样的行:streampos line=file.tellg();

关于c++ - 用 fstream 在最后一行写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35165320/

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