首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用fstream在最后一行上写

用fstream在最后一行上写
EN

Stack Overflow用户
提问于 2016-02-02 22:50:25
回答 1查看 403关注 0票数 1

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

以下是代码:

代码语言:javascript
运行
复制
#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! 嗨,我的名字是阿米尔,我朋友的名字也是阿米尔!

最后一行怎么了?

我想问题就在这里:

代码语言:javascript
运行
复制
if (flagforwrite){ 
                    file.seekp(flag);
                    file << buffer << "\n";
                    if(file.bad()) cout << "Error\n";
            }

为什么旗子总是指线?

我用GNU GCC编译器。

EN

回答 1

Stack Overflow用户

发布于 2016-02-03 09:14:31

我发现问题了!这是由eof()引起的!所以,我没有使用while(!file.eof()),而是使用了while(file.getline(buffer,100))

我还将file.tellg()移到末尾,并定义了如下行:streampos line=file.tellg();

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35165320

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档