我试图替换文本文件中的一个字符串。类似于替换()函数。
以下是代码:
#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;
}
我想把"amir“改为"reza”。
我的文本文件包括4行:
嗨,我的名字是阿米尔,我朋友的名字也是阿米尔! 嗨,我的名字是阿米尔,我朋友的名字也是阿米尔! 嗨,我的名字是阿米尔,我朋友的名字也是阿米尔! 嗨,我的名字是阿米尔,我朋友的名字也是阿米尔!
当我运行这个程序时,我会得到这个。
你好,我的名字是reza,我朋友的名字也叫reza! 你好,我的名字是reza,我朋友的名字也叫reza! 你好,我的名字是reza,我朋友的名字也叫reza! 嗨,我的名字是阿米尔,我朋友的名字也是阿米尔!
最后一行怎么了?
我想问题就在这里:
if (flagforwrite){
file.seekp(flag);
file << buffer << "\n";
if(file.bad()) cout << "Error\n";
}
为什么旗子总是指线?
我用GNU GCC编译器。
发布于 2016-02-03 09:14:31
我发现问题了!这是由eof()引起的!所以,我没有使用while(!file.eof())
,而是使用了while(file.getline(buffer,100))
我还将file.tellg()移到末尾,并定义了如下行:streampos line=file.tellg();
https://stackoverflow.com/questions/35165320
复制相似问题