I was trying to write a script with c++... This Script will replace a string with something else on a text file... something like replace() function
I'm almost done, but apparently there is a bug in my program which I can't find!!
Here is the code:
#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;
}
SO I wanna replace "amir" with "reza".
My text Files includes 4 lines:
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!
and When I Run The Program I get This!!
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!
What Is wrong with last line?!
I definitely think that problem is here:
if (flagforwrite){
file.seekp(flag);
file << buffer << "\n";
if(file.bad()) cout << "Error\n";
}
But why?! flag is always referring to the line, everything's fine until last line!
I'm Using GNU GCC compiler. I'll Appreciate your help, Thank you.
Aucun commentaire:
Enregistrer un commentaire