当前位置: 首页 > news >正文

C++的IO流

1. C语言的输入与输出

C语言中我们用到的最频繁的输入输出方式就是scanf ()与printf()scanf(): 从标准输入设备(键盘)读取数据,并将值存放在变量中printf(): 将指定的文字/字符串输出到标准输出设备(屏幕)注意宽度输出和精度输出控制。C语言借助了相应的缓冲区来进行输入与输出。如下图所示:

image-20221010131532713

输入输出缓冲区的理解:

  1. 可以屏蔽掉低级I/O的实现,低级I/O的实现依赖操作系统本身内核的实现,所以如果能够屏蔽这部分的差异,可以很容易写出可移植的程序
  2. 可以使用这部分的内容实现“行”读取的行为,对于计算机而言是没有“行”这个概念,有了这部分,就可以定义“行”的概念,然后解析缓冲区的内容,返回一个“行”。

2. 流是什么

“流”即是流动的意思,是物质从一处向另一处流动的过程,是对一种有序连续且具有方向性的数据( 其单位可以是bit,byte,packet )的抽象描述。

C++流是指信息从外部输入设备(如键盘)向计算机内部(如内存)输入和从内存向外部输出设备(显示器)输出的过程。这种输入输出的过程被形象的比喻为“流”。

它的特性是:有序连续、具有方向性

为了实现这种流动,C++定义了I/O标准类库,这些每个类都称为流/流类,用以完成某方面的功能

3. C++IO流

C++系统实现了一个庞大的类库,其中ios为基类,其他类都是直接或间接派生自ios类

image-20221010133659440

特性:

1、面向对象

2、针对自定义类型对象

3.1 C++标准IO流

C++标准库提供了4个全局流对象cin、cout、cerr、clog,使用cout进行标准输出,即数据从内存流向控制台(显示器)。使用cin进行标准输入即数据通过键盘输入到程序中,同时C++标准库还提供了cerr用来进行标准错误的输出,以及clog进行日志的输出,从上图可以看出,cout、 cerr、clog是ostream类的三个不同的对象,因此这三个对象现在基本没有区别,只是应用场景不同。

在使用时候必须要包含文件并引入std标准命名空间

注意

  1. cin为缓冲流。键盘输入的数据保存在缓冲区中,当要提取时,是从缓冲区中拿。如果一次输入过多,会留在那儿慢慢用,如果输入错了,必须在回车之前修改,如果回车键按下就无法挽回了。只有把输入缓冲区中的数据取完后,才要求输入新的数据

  2. 输入的数据类型必须与要提取的数据类型一致,否则出错。出错只是在流的状态字state中对 应位置位(置1),程序继续。

  3. 空格和回车都可以作为数据之间的分格符,所以多个数据可以在一行输入,也可以分行输 入。但如果是字符型和字符串,则空格(ASCII码为32)无法用cin输入,字符串中也不能有空格。回车符也无法读入。

  4. cin和cout可以直接输入和输出内置类型数据,原因:标准库已经将所有内置类型的输入和输出全部重载了:

    image-20221012093115379

    image-20221012093148670

  5. 对于自定义类型,如果要支持cin和cout的标准输入输出,需要对<<和>>进行重载。

  6. 在线OJ中的输入和输出:

    • 对于IO类型的算法,一般都需要循环输入:

    • 输出:严格按照题目的要求进行,多一个少一个空格都不行。

    • 连续输入时,vs系列编译器下在输入ctrl+Z时结束(linux下是不可以的,Linux下ctrl+Z是将进程挂起,还需要自己杀死,Linux下需要用ctrl+c,给进程发送一个信号,将进程杀掉)

      // 单个元素循环输入
      while(cin>>a)
      {
          // ...
      }
      // 多个元素循环输入
      while(c>>a>>b>>c)
      {
          // ...
      }
      // 整行接收
      while(cin>>str)
      {
          // ...
      }
      
  7. istream类型对象转换为逻辑条件判断值

    思考一下上面的cin>>str为什么可以当作while中的判断条件?

    cin >> str   ---------> operator >> (cin, str)
    

    image-20221012095058557

    上述函数返回类型为istream类型的对象即cin。

    又因为istream类重载了operator bool函数,会隐式类型转换为bool类型的对象

    image-20221012100227845

    image-20221012100057695

    class Date
    {
        friend ostream& operator << (ostream& out, const Date& d);
        friend istream& operator >> (istream& in, Date& d);
    public:
        Date(int year = 1, int month = 1, int day = 1)
            :_year(year)
            , _month(month)
            , _day(day)
        {}
        operator bool()
        {
            // 这里是随意写的,假设输入_year为0,则结束
            if (_year == 0)
                return false;
            else
                return true;
        }
    private:
        int _year;
        int _month;
        int _day;
    };
    istream& operator >> (istream& in, Date& d)
    {
        in >> d._year >> d._month >> d._day;
        return in;
    }
    ostream& operator << (ostream& out, const Date& d)
    {
        out << d._year << " " << d._month << " " << d._day;
        return out;
    }
    // C++ IO流,使用面向对象+运算符重载的方式
    // 能更好的兼容自定义类型,流插入和流提取
    int main()
    {
        // 自动识别类型的本质--函数重载
        // 内置类型可以直接使用--因为库里面ostream类型已经实现了
        int i = 1;
        double j = 2.2;
        cout << i << endl;
        cout << j << endl;
        // 自定义类型则需要我们自己重载<< 和 >>
        Date d(2022, 4, 10);
        cout << d;
        while (d)
        {
            cin >> d;
            cout << d;
        }
        return 0;
    }
    

注意:cin慢是有原因的,其实默认的时候,cin与stdin总是保持同步的,也就是说这两种方法可以混用,而不必担心文件指针混乱,同时cout和stdout也一样,两者混用不会输出顺序错乱。正因为这个兼容性的特性,导致cin有许多额外的开销,如何禁用这个特性呢?只需一个语句std::ios::sync_with_stdio(false);,这样就可以取消cin于stdin的同步了,进而提高cin的效率了,cin读取的也就更快。

image-20221012105238810

3.2 C++文件IO流

C++根据文件内容的数据格式分为二进制文件和文本文件。采用文件流对象操作文件的一般步骤:

  1. 定义一个文件流对象

    • ifstream ifile(只输入用)

      image-20221012111545371

      image-20221012111600315

    • ofstream ofile(只输出用)

    • fstream iofile(既输入又输出用)

  2. 使用文件流对象的成员函数打开一个磁盘文件,使得文件流对象和磁盘文件之间建立联系

  3. 使用提取和插入运算符对文件进行读写操作,或使用成员函数进行读写

  4. 关闭文件

简单使用举例:

int main()
{
   ifstream ifs("Test.cpp");
   while(ifs)
   {
     char ch = ifs.get();
     cout << ch;
   }
   return 0;
}

运行截图:

image-20221012114406015

问:此处为什么可以使用while(ifs)?

答:因为iostream继承的是ios,而operator bool是在ios中的重载的。

当然,也可以像下面这样写:

int main()
{
   ifstream ifs("Test.cpp");
   char ch;
   while(ifs)
   {
     ifs >> ch;
     cout << ch;
   }
   return 0;
}

运行截图:

image-20221012114003350

问:如何复制一份当前的文件?

答:

代码:

int main()
{
	ifstream ifs("Test.cpp");
	ofstream ofs("Copy.cpp");
	char ch;
	while (~(ch = ifs.get()))
	{
		ofs << ch;
	}
	return 0;
}

通过上面的代码,即可实现拷贝Test.cpp文件中的内容到新的文件Cop.cpp中。

注意:二进制形式读写不能将string类型的数据写到文件中,因为string类中存储的是指针,并不是有效的数据,当新的进程尝试从相应的指针中读取文件的时候,相应的位置中存储的内容已经发生改变或者并不具有读写权限,此时程序就会出错。

class Date
{
    friend ostream& operator << (ostream& out, const Date& d);
    friend istream& operator >> (istream& in, Date& d);
public:
    Date(int year = 1, int month = 1, int day = 1)
        :_year(year)
        , _month(month)
        , _day(day)
    {}
    operator bool()
    {
        // 这里是随意写的,假设输入_year为0,则结束
        if (_year == 0)
            return false;
        else
            return true;
    }
private:
    int _year;
    int _month;
    int _day;
};

istream& operator >> (istream& in, Date& d)
{
    in >> d._year >> d._month >> d._day;
    return in;
}
ostream& operator << (ostream& out, const Date& d)
{
    out << d._year << " " << d._month << " " << d._day;
    return out;
}
struct ServerInfo
{
    char _address[100];
    int _port;
    Date _date;
};
struct ConfigManager
{
public:
    ConfigManager(const char* filename)
        :_filename(filename)
    {}
    void WriteBin(const ServerInfo& info)
    {
        ofstream ofs(_filename, ios_base::out | ios_base::binary);
        ofs.write((const char*)&info, sizeof(info));
    }
    void ReadBin(ServerInfo& info)
    {
        ifstream ifs(_filename, ios_base::in | ios_base::binary);
        ifs.read((char*)&info, sizeof(info));
    }
    // C++文件流的优势就是可以对内置类型和自定义类型,都使用
    // 一样的方式,去流插入和流提取数据
    // 当然这里自定义类型Date需要重载>> 和 <<
    // istream& operator >> (istream& in, Date& d)
     // ostream& operator << (ostream& out, const Date& d)
    void WriteText(const ServerInfo& info)
    {
        ofstream ofs(_filename);
        ofs << info._address << " " << info._port << " " << info._date;
    }
    void ReadText(ServerInfo& info)
    {
        ifstream ifs(_filename);
        ifs >> info._address >> info._port >> info._date;
    }
private:
    string _filename; // 配置文件
};

int main()
{
    ServerInfo info = { "https://legacy.cplusplus.com/reference/ios/ios/operator_bool/", 80, {2022, 10, 12} };
    //二进制的方式读写
    //ConfigManager cf_bin("testBin.cpp");
    //cf_bin.WriteBin(info);//将info数据写到"testBin.cpp"文件中

    //ServerInfo rbinfo;
    //cf_bin.ReadBin(rbinfo);//将"testBin.cpp"文件中的内容写到rbinfo对象中
    //cout << rbinfo._address << " " << rbinfo._port " " << rtinfo._date << endl;
    
    //文本的方式读写
    ConfigManager cf_txt("testTxt.cpp");//将info数据写道"testTxt.cpp"文件中
    cf_txt.WriteText(info);

    ServerInfo rtinfo;
    cf_txt.ReadText(rtinfo);//将"testTxt.cpp"文件中的内容写到rtinfo对象中
    cout << rtinfo._address << " " << rtinfo._port << " " << rtinfo._date << endl;
    return 0;
}

4. stringstream的简单介绍

在C语言中,如果想要将一个整形变量的数据转化为字符串格式,如何去做?

  1. 使用itoa()函数
  2. 使用sprintf()函数

但是两个函数在转化时,都得需要先给出保存结果的空间,那空间要给多大呢,就不太好界定, 而且转化格式不匹配时,可能还会得到错误的结果甚至程序崩溃。

int main()
{
	int n = 123456789;
	char s1[32];
	_itoa(n, s1, 10);
	char s2[32];
	sprintf(s2, "%d", n);
	char s3[32];
	sprintf(s3, "%f", n);
	return 0;
}

在C++中,可以使用stringstream类对象来避开此问题。

在程序中如果想要使用stringstream,必须要包含头文件。在该头文件下,标准库三个类: istringstream、ostringstream 和 stringstream,分别用来进行流的输入、输出和输入输出操作,本文主要介绍stringstream。

stringstream主要可以用来:

  1. 将数值类型数据格式化为字符串

    int main()
    {
        stringstream s;
        int a = 12345;
        string sa;
    
        s << a;
        s >> sa;
        cout << sa << endl;
        // clear()
        // 注意多次转换时,必须使用clear将上次转换状态清空掉
        // stringstreams在转换结尾时(即最后一个转换后),会将其内部状态设置为badbit
        // 因此下一次转换是必须调用clear()将状态重置为goodbit才可以转换
        // 但是clear()不会将stringstreams底层字符串清空掉
    
        // s.str("");
        // 将stringstream底层管理string对象设置成"", 
        // 否则多次转换时,会将结果全部累积在底层string对象中
        s.str("");
        s.clear();
        double d = 3.14159;
        string sd;
        s << d;
        s >> sd;
        cout << sd;
        return 0;
    }
    

    运行截图:

    image-20221012150208495

  2. 字符串拼接

    int main()
    {
        stringstream sstream;
        //将多个字符串放入到sstream中
        sstream << "hello";
        sstream << " ";
        sstream << "world";
        sstream << endl;
        cout << "strResult is: " << sstream.str();
    
        //清空sstream
        sstream.str("");
        sstream << "hello " << "first " << "second" << endl;
        cout << sstream.str();
        return 0;
    }
    

    image-20221012150835723

  3. 序列化和反序列化结构数据

    int main()
    {
        Date d1 = { 2022, 10, 12 };
        Date d2;
        stringstream s;
        s << d1;
        s >> d2;
        cout << d2 << endl;
        s.clear();
        //清空s中的数据
        s.str("");
        return 0;
    }
    

    运行截图:

    image-20221012150811404

istringstream和ostringstream分别来使用:

class Date
{
    friend ostream& operator << (ostream& out, const Date& d);
    friend istream& operator >> (istream& in, Date& d);
public:
    Date(int year = 1, int month = 1, int day = 1)
        :_year(year)
        , _month(month)
        , _day(day)
    {}
    operator bool()
    {
        // 这里是随意写的,假设输入_year为0,则结束
        if (_year == 0)
            return false;
        else
            return true;
    }
private:
    int _year;
    int _month;
    int _day;
};

istream& operator >> (istream& in, Date& d)
{
    in >> d._year >> d._month >> d._day;
    return in;
}
ostream& operator << (ostream& out, const Date& d)
{
    out << d._year << " " << d._month << " " << d._day;
    return out;
}
int main()
{
	int i = 123456;
	double d = 3.14159;
    Date date(2022, 10, 12);

	ostringstream oss;
	oss << i;
	string stri = oss.str();
	cout << stri << endl;

	oss.str("");

	oss << d;
	string strd = oss.str();
	cout << strd << endl;

	oss.str("");

    oss << date;
    string strdate = oss.str();
    cout << strdate << endl;

    istringstream iss(strdate);
    Date d2;
    iss >> d2;
    cout << d2;
	return 0;
}

运行截图:

image-20221012145737769

注意:

  1. stringstream实际是在其底层维护了一个string类型的对象用来保存结果
  2. 多次数据类型转化时,一定要用clear()来清空,才能正确转化,但clear()不会将 stringstream底层的string对象清空。
  3. 可以使用s. str(“”)方法将底层string对象设置为""空字符串
  4. 可以使用s.str()将让stringstream返回其底层的string对象
  5. stringstream使用string类对象代替字符数组,可以避免缓冲区溢出的危险,而且其会对参 数类型进行推演,不需要格式化控制,也不会出现格式化失败的风险,因此使用更方便,更安全。

相关文章:

  • hackmyvm-jan
  • 如何在 React 项目中使用React.lazy和Suspense实现组件的懒加载?
  • Linux进程间的通信
  • 如何将3DMax模型转换到Blender?
  • 51单片机
  • 基于代理(http\https\socks)的网络访问逻辑重定义
  • 基于本人的专利设计三角形式的三组定子和中间的分形转子结构
  • 海外营收占比近4成,泡泡玛特全球化战略迎收获期
  • 33.[前端开发-JavaScript基础]Day10-常见事件-鼠标事件-键盘事件-定时器-案例
  • C++ 继承:面向对象编程的核心概念(二)
  • 中文字符计数器,助力所有python对齐业务(DeepSeek代笔)
  • 青藏高原湖泊的数量越来越多
  • Mem0 Prompt优化
  • 从手机到机器人:vivo 凭借用户主义重构科技价值
  • 旋转式花键在哪些工业领域应用较为广泛?
  • wps如何给word加水印
  • 告别AI幻觉:Cursor“知识库”技术实现85%的错误减少
  • word写latex-Mathtype安装成功-方法
  • 练习题:105
  • 电脑上我的windows目录下,什么是可以删除的
  • 网文书单|推荐4本网文,可以当作《绍宋》代餐
  • 2025年上海科技节开幕,人形机器人首次登上科学红毯
  • 首映|《星际宝贝史迪奇》真人电影,不变的“欧哈纳”
  • 当智慧农场遇见绿色工厂:百事如何用科技留住春天的味道?
  • 关税互降后的外贸企业:之前暂停的订单加紧发货,后续订单考验沟通谈判能力
  • 中期选举后第三势力成“莎拉弹劾案”关键,菲律宾权斗更趋复杂激烈