Absolute C++ 2.10题目

感谢伟大的CSS!微笑

题目描述:

创建一个内容为“I hate C++ and hate programming!"的文本文件。编写程序读取该文件的内容,并将其中出现的”hate“全部替换成”love“后,输出到控制台。编写的程序应具有通用性,可以正确处理其他的文本文件。

代码如下:

/*
Create "playing.txt" in the present directory,
which contains "I hate C++ and hate Programming",
Your task is to exchange all the "hate" in the text with "like",
and after that you'll get "I like C++ and like Programming."
*/
#include <iostream>
#include<string.h>
#include<fstream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;

int main()
{
    //string verb;
    char verb;
    fstream change;
    change.open("playing.txt");
    int now=0;
    int flag=0;
    change.get(verb);
    //loop:there is some unknown logical problems with it.
    while(!change.eof())
    {
        printf(" verb=%c now=%d
",verb,now);
        if(flag==0 && verb=='h'){
            flag++;
        }
        else if(flag==1 && verb=='a'){
            flag++;
        }
        else if(flag==2 && verb=='t'){
            flag++;
        }
        else if(flag==3 && verb=='e'){
            flag=0;
            change.seekp(sizeof(char)*(now-3),ios::beg);
            change<<"love";
        }
        else{
            flag=0;
        }
        now++;
        change.get(verb);
        /*
        if(verb=="hate")
        {
            change.seekp(now,ios::beg);
            //change<<"";  //backspace
            change<<"love";
        }*/
        //now++;
    }
    change.close();
}

/*
五、文件定位
  和C的文件操作方式不同的是,C++ I/O系统管理两个与一个文件相联系的指针。一个是读指针,它说明输入操作在文件中的位置;另一个是写指针,它下次写操作的位置。每次执行输入或输出时,相应的指针自动变化。所以,C++的文件定位分为读位置和写位置的定位,对应的成员函数是 seekg()和 seekp(),seekg()是设置读位置,seekp是设置写位置。它们最通用的形式如下:

    istream &seekg(streamoff offset,seek_dir origin);
    ostream &seekp(streamoff offset,seek_dir origin);

  streamoff定义于 iostream.h 中,定义有偏移量 offset 所能取得的最大值,seek_dir 表示移动的基准位置,是一个有以下值的枚举:

ios::beg:  文件开头
ios::cur:  文件当前位置
ios::end:  文件结尾
  这两个函数一般用于二进制文件,因为文本文件会因为系统对字符的解释而可能与预想的值不同。

例:

     file1.seekg(1234,ios::cur);//把文件的读指针从当前位置向后移1234个字节
     file2.seekp(1234,ios::beg);//把文件的写指针从文件开头向后移1234个字节
*/

版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/Tobyuyu/p/4965725.html