• C++——IO流


    目录

    一.C语言的输入与输出

    二.C++标准IO流

    1.流是什么

    2.C++IO流

    三.C++文件IO流 

    四.stringstream的简单介绍

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

    2. 字符串拼接 

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


    62a9af733a384df1a2058b1cc88ab146.gif

    一.C语言的输入与输出

    C语言中我们用到的最频繁的输入输出方式就是scanf ()与printf()。 scanf(): 从标准输入设备(键
    盘)读取数据,并将值存放在变量中。printf(): 将指定的文字/字符串输出到标准输出设备(屏幕)。

    C语言借助了相应的缓冲区来进行输入与输出。如下图所示:

    eb6ae0794139444bb51b6f6725a5ba9e.png

    对输入输出缓冲区的理解: 

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

    二.C++标准IO流

    1.流是什么

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

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

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

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

    2.C++IO流

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

    b5e084fa2d664ce8af899b92b262f213.png

    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可以直接输入和输出内置类型数据,原因:标准库已经将所有内置类型的输入和输出全部重载了:
    5. 对于自定义类型,如果要支持cin和cout的标准输入输出,需要对<<和>>进行重载。
       

     在线OJ中的输入和输出:

    • 对于IO类型的算法,一般都需要循环输入:
    • 输出:严格按照题目的要求进行,多一个少一个空格都不行。
    • 连续输入时,vs系列编译器下在输入ctrl+Z时结束

    8a37f6c8a9994715af7dfb115f93c63a.png

    实际上我们看到使用while(cin>>i)去流中提取对象数据时,调用的是operator>>,返回值是
    istream类型的对象,那么这里可以做逻辑条件值,源自于istream的对象又调用了operator
    bool,operator bool调用时如果接收流失败,或者有结束标志,则返回false。

    1. istream& operator>> (int& val);
    2. explicit operator bool() const;

    例如:

    1. class Date
    2. {
    3. friend ostream& operator << (ostream& out, const Date& d);
    4. friend istream& operator >> (istream& in, Date& d);
    5. public:
    6. Date(int year = 1, int month = 1, int day = 1)
    7. :_year(year)
    8. , _month(month)
    9. , _day(day)
    10. {}
    11. operator bool()
    12. {
    13. // 这里是随意写的,假设输入_year为0,则结束
    14. if (_year == 0)
    15. return false;
    16. else
    17. return true;
    18. }
    19. private:
    20. int _year;
    21. int _month;
    22. int _day;
    23. };
    24. istream& operator >> (istream& in, Date& d)
    25. {
    26. in >> d._year >> d._month >> d._day;
    27. return in;
    28. }
    29. ostream& operator << (ostream& out, const Date& d)
    30. {
    31. out << d._year << " " << d._month << " " << d._day;
    32. return out;
    33. }
    34. // C++ IO流,使用面向对象+运算符重载的方式
    35. // 能更好的兼容自定义类型,流插入和流提取
    36. int main()
    37. {
    38. Date d;
    39. while (d)
    40. {
    41. cin >> d;
    42. cout << d;
    43. }
    44. return 0;
    45. }

    ae6f01778ead47719468f2b59177a85c.png

    三.C++文件IO流 

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

    1. 定义一个文件流对象。

    • ifstream ifile(只输入用)
    • ofstream ofile(只输出用)
    • fstream iofile(既输入又输出用)

    2. 使用文件流对象的成员函数打开一个磁盘文件,使得文件流对象和磁盘文件之间建立联系。
    3. 使用提取和插入运算符对文件进行读写操作,或使用成员函数进行读写。
    4. 关闭文件。

    1. class Date
    2. {
    3. friend ostream& operator << (ostream& out, const Date& d);
    4. friend istream& operator >> (istream& in, Date& d);
    5. public:
    6. Date(int year = 1, int month = 1, int day = 1)
    7. :_year(year)
    8. , _month(month)
    9. , _day(day)
    10. {}
    11. operator bool()
    12. {
    13. // 这里是随意写的,假设输入_year为0,则结束
    14. if (_year == 0)
    15. return false;
    16. else
    17. return true;
    18. }
    19. private:
    20. int _year;
    21. int _month;
    22. int _day;
    23. };
    24. istream& operator >> (istream& in, Date& d)
    25. {
    26. in >> d._year >> d._month >> d._day;
    27. return in;
    28. }
    29. ostream& operator << (ostream& out, const Date& d)
    30. {
    31. out << d._year << " " << d._month << " " << d._day;
    32. return out;
    33. }
    34. struct ServerInfo
    35. {
    36. char _address[32];
    37. int _port;
    38. Date _date;
    39. };
    40. struct ConfigManager
    41. {
    42. public:
    43. ConfigManager(const char* filename)
    44. :_filename(filename)
    45. {}
    46. void WriteBin(ServerInfo& info)
    47. {
    48. //二进制流输出的方式创建一个文件对象
    49. ofstream ofs(_filename, ios_base::out | ios_base::binary);
    50. ofs.write((const char*)&info,sizeof(info));
    51. }
    52. void ReadBin(ServerInfo& info)
    53. {
    54. //二进制流输入的方式创建一个文件对象
    55. ifstream ifs(_filename, ios_base::in | ios_base::binary);
    56. ifs.read((char*)&info, sizeof(info));
    57. }
    58. void WriteText(const ServerInfo& info)
    59. {
    60. ofstream ofs(_filename);
    61. ofs << info._address << " " << info._port << " " << info._date;
    62. }
    63. void ReadText(ServerInfo& info)
    64. {
    65. ifstream ifs(_filename);
    66. ifs >> info._address >> info._port >> info._date;
    67. }
    68. private:
    69. string _filename; // 配置文件
    70. };
    71. int main()
    72. {
    73. ServerInfo winfo = { "192.0.0.1", 80, { 2022, 4, 10 } };
    74. // 二进制读写
    75. ConfigManager cf_bin("test.bin");
    76. cf_bin.WriteBin(winfo);
    77. ServerInfo rbinfo;
    78. cf_bin.ReadBin(rbinfo);
    79. cout << rbinfo._address << " " << rbinfo._port << " "
    80. << rbinfo._date << endl;
    81. // 文本读写
    82. ConfigManager cf_text("test.text");
    83. cf_text.WriteText(winfo);
    84. ServerInfo rtinfo;
    85. cf_text.ReadText(rtinfo);
    86. cout << rtinfo._address << " " << rtinfo._port << " " <<
    87. rtinfo._date << endl;
    88. return 0;
    89. }

    34433f5dd86046f5b6ccc87e6e705045.png

    四.stringstream的简单介绍

    在C语言中,如果想要将一个整形变量的数据转化为字符串格式,如何去做?
    1. 使用itoa()函数
    2. 使用sprintf()函数
    但是两个函数在转化时,都得需要先给出保存结果的空间,那空间要给多大呢,就不太好界定,
    而且转化格式不匹配时,可能还会得到错误的结果甚至程序崩溃

    1. int main()
    2. {
    3. int n = 123456789;
    4. double f = 12345.6789;
    5. char s1[32];
    6. _itoa(n, s1, 10);
    7. char s2[32];
    8. sprintf(s2, "%d", n);
    9. char s3[32];
    10. sprintf(s3, "%f", f);
    11. cout << "s3:" << s3 << endl;
    12. cout << "s2:" << s2 << endl;
    13. cout << "s1:" << s1 << endl;
    14. return 0;
    15. }

    a1521e399c6d4bb88051810b1dffa613.png

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

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

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

    1. #include
    2. int main()
    3. {
    4. int a = 12345678;
    5. string sa;
    6. // 将一个整形变量转化为字符串,存储到string类对象中
    7. stringstream s;
    8. s << a;
    9. s >> sa;
    10. cout << sa << endl;
    11. // clear()
    12. // 注意多次转换时,必须使用clear将上次转换状态清空掉
    13. // stringstreams在转换结尾时(即最后一个转换后),会将其内部状态设置为badbit
    14. // 因此下一次转换是必须调用clear()将状态重置为goodbit才可以转换
    15. // 但是clear()不会将stringstreams底层字符串清空掉
    16. // s.str("");
    17. // 将stringstream底层管理string对象设置成"",
    18. // 否则多次转换时,会将结果全部累积在底层string对象中
    19. s.str("");
    20. s.clear(); // 清空s, 不清空会转化失败
    21. double d = 12.34;
    22. s << d;
    23. s >> sa;
    24. string sValue;
    25. sValue = s.str(); // str()方法:返回stringsteam中管理的string类型
    26. cout << sValue << endl;
    27. return 0;
    28. }

    79dc8caad171476ebadc5d00864ddbcb.png

    2. 字符串拼接 

    1. int main()
    2. {
    3. stringstream s;
    4. // 将多个字符串放入 s 中
    5. s << "first" << " " << "string";
    6. s << " second string";
    7. cout << "strResult is: " << s.str() << endl;
    8. string s1;
    9. string s2;
    10. //从s中提取字符串
    11. s >> s1;
    12. s >> s2;
    13. cout << s1 << endl;
    14. cout << s2 << endl;
    15. return 0;
    16. }

    98f5a3fdec9f4ba08409493a69be4e87.png

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

     

    1. struct ChatInfo
    2. {
    3. string _name;// 名字
    4. int _id; // id
    5. Date _date; // 时间
    6. string _msg; // 聊天信息
    7. };
    8. int main()
    9. {
    10. // 结构信息序列化为字符串
    11. ChatInfo winfo = { "张三", 135246, { 2022, 4, 10 }, "晚上一起看电影吧"};
    12. ostringstream oss;
    13. oss << winfo._name << " " << winfo._id << " " << winfo._date << " "
    14. << winfo._msg;
    15. string str = oss.str();
    16. cout << str << endl << endl;
    17. // 我们通过网络这个字符串发送给对象,实际开发中,信息相对更复杂,
    18. // 一般会选用Json、xml等方式进行更好的支持
    19. // 字符串解析成结构信息
    20. ChatInfo rInfo;
    21. istringstream iss(str);
    22. iss >> rInfo._name >> rInfo._id >> rInfo._date >> rInfo._msg;
    23. cout << "-------------------------------------------------------"
    24. << endl;
    25. cout << "姓名:" << rInfo._name << "(" << rInfo._id << ") ";
    26. cout << rInfo._date << endl;
    27. cout << rInfo._name << ":>" << rInfo._msg << endl;
    28. cout << "-------------------------------------------------------"
    29. << endl;
    30. return 0;
    31. }

    d803353897b84e03b1c07faa8df1ebe8.png

     

  • 相关阅读:
    剖析 Kubernetes 控制器:Deployment、ReplicaSet 和 StatefulSet 的功能与应用场景
    “农场”技术栈是什么?浅聊FARM Stack
    09/10的一周
    Docker 在 M1 Mac arm64架构上构建 amd64镜像。
    2024-06-02 问AI: 在大语言模型中,什么是multi agent?
    Zabbix使用手册
    区间搜索指令(博途SCL)
    LeetCode·376.摆动序列·贪心·动态规划
    进化的京东云DaaS:向大模型要解
    E. Till I Collapse
  • 原文地址:https://blog.csdn.net/qq_63943454/article/details/133998458