听专情的古人,把美言留给最爱的人........................................................................................
文章目录
前言
本篇博客主要介绍了C++中的输入输出流,主要包括<iostream>,<fstream>,<sstream>,三种流,涉及他们的用法以及注意事项,请耐心关键看!
一、【C/C++ IO流】
1、【C语言的输入与输出】
在C语言当中,我们使用最频繁的输入输出方式就是scanf与printf:
- scanf: 从标准输入设备(键盘)读取数据,并将读取到的值存放到某一指定变量当中。
- printf: 将指定的数据输出到标准输出设备(屏幕),使用时需要注意宽度输出和精度输出的控制。
C语言借助了相应的缓冲区来进行输入与输出,如下图所示:
对输入输出缓冲区的理解:
- 可以屏蔽掉低级I/O的实现。 低级I/O的实现依赖操作系统本身内核的实现,所以如果能够屏蔽这部分的差异,可以很容易写出可移植的程序。
- 可以使用这部分的内容实现“行”读取的行为。 对于计算机而言是没有“行”这个概念的,有了这部分,就可以定义“行”的概念,然后解析缓冲区的内容,返回一个“行”。
关于C语言其他的的输入输出请看博客——>【【C语言中的文件操作】-优快云博客】
2、【C++IO流引入】
首先我们先谈谈什么是流:
流”即是流动的意思,是物质从一处向另一处流动的过程,是对一种有序连续且有方向性的数据的抽象描述。C++流是指信息从外部输入设备(如键盘)向计算机内部(如内存)输入和从计算机内部向外部输出设备(如显示器)输出的过程。这种输入输出的过程被形象的比喻为“流”。流具有,有序,连续、方向性的特点,为了实现这种流动,C++定义了I/O标准类库,当中的每个类都称为流/流类,用以完成某方面的功能。
C++系统实现了一个庞大的类库,其中ios为基类,其他类都是直接或间接派生自ios类。
图中箭头指的是各个类之间的派生关系。可以看到,其中主要包括<iostream>,<fstream>,<sstream>,其中好像还有菱形继承的存在,与C语言的输入输出对应如下:
C++为什么要设计一套IO流的库呢?
C语言是不能支持自定义类型的打印的。C++为了能够支持复杂类型的打印,设计了这样一套io流的库,如果需要对自定义类型进行打印,则可以通过运算符重载来进行自定义输入、输出,并且C++对C语言的输入输出也都兼容。
二、【C++标准IO流——<iostream>】
2.1、【cin&&cout】
C++标准库提供了4个全局流对象(cin、cout、cerr、clog):
- 使用cout进行标准输出,即数据从内存流向控制台(显示器)。
- 使用cin进行标准输入,即数据通过键盘输入到程序中。
- 使用cerr进行标准错误的输出。
- 使用clog进行日志的输出。
- cout、cerr、clog都是由ostream类实例化出的三个不同的对象,因此这三个对象基本没什么区别,只是应用场景不同。
下面在使用cin和cout时要注意的点:
1、在使用cin、cout时必须要包含iostream文件,并引入std标准命名空间。
#include <iostream> //包含iostream文件 using namespace std; //引入std标准命名空间 int main() { int a = 0; cin >> a; cout << a << endl; return 0; }
结果:
或是在使用时指定cout和cin所属的命名空间,像下面这样:
#include <iostream> //包含iostream文件 int main() { int a = 0; std::cin >> a; //使用时指定所属命名空间 std::cout << a << std::endl; //使用时指定所属命名空间 return 0; }
结果是一样的:
2、cin为缓冲流。键盘输入的数据保存在缓冲区中,当要提取时,是从缓冲区中提取。
如果一次输入过多,则多余的数据会留在缓冲区以供之后提取,如果输入错了,必须在回车之前进行修改,回车键按下就无法进行修改了,只有把输入缓冲区中的数据取完后,才会要求输入新的数据。
例如,对于以下代码,若在第一次输入时便以空格为分隔输入了两个数据,则在下一次需要提取数据的时候就直接从缓冲区进行提取。#include <iostream> using namespace std; int main() { int a = 0, b = 0; cin >> a; //输入:10 20 cout << a << endl; cin >> b; //直接从输入缓冲区提取 cout << b << endl; return 0; }
结果:
4、cin和cout可以直接输入和输出内置类型的数据。因为标准库已经将所有内置类型的输入和输出进行了重载。
5、对于自定义类型,如果要支持cin和cout的标准输入输出,则需要对<<和>>进行重载。
例如,对于下面简单实现的日期类,在对<<和>>进行重载后就能够支持cin和cout的输入输出了。#include <iostream> using namespace std; class Date { friend istream& operator>>(istream& in, Date& d); friend ostream& operator<<(ostream& out, const Date& d); public: Date(int year = 2022, int month = 1, int day = 1) :_year(year) , _month(month) , _day(day) {} 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() { Date d; cin >> d; //输入:2024 3 21 cout << d << endl; //输出:2024-3-21 return 0; }
结果:
2.2、【隐藏的类型转换】
我们之前可能写过C语言的OJ题见到过如下的使用场景:
while (scanf("%d", &a) != EOF) { //... }
在C++当中,对应如下:
while (cin >> a) { //... }
我们可能会好奇,为什么cin>>a可以作为while循环的判断语句,难道该函数有返回值吗?
我们来看下面这样一个例子:
int main() { string str; while (cin >> str) { cout << str << endl; } return 0; }
我们会发现我们总是能一直输入,那么该怎么让程序停下来呢?一般有两种做法,分别是使用ctrl+c,ctrl+z+回车:
那么他是怎么做到的呢?我们可以去查一下 string 类的流提取。
这个地方的本质就是调用这个函数。如下:
int main() { string str; //while (cin >> str) while (operator>>(cin, str)) { cout << str << endl; } return 0; }
我们发现它的返回值是一个istream 的对象,一个 istream 的对象是不能做条件逻辑判断的,那么这里能实现是因为C++在istream内部 重载了一个operator bool ,如下:
int main() { string str; //while (cin >> str) while (operator>>(cin, str).operator bool()) { cout << str << endl; } return 0; }
也就是说,istream在内部实现了一个方法,使其能转换为一个bool类型,大概类似于下面这样:
class istream { public: operator bool()//这里返回值和要重载的都是bool所以为了不重复,就写了一个 { // ... if() { return true; } else { return false; } } };
那么就意味着我们也可以自己在自定义类型中进行类型转换,只需要我们自己提供成员方法即可:
class E { public: operator int() { // ... return 256; } }; int main() { E e; int x = e; cout << x << endl; return 0; }
那么我们就实现了自定义类型到内置类型的转换,至此类型转换实现彻底闭环:
#include<list> class C { public: C(int x) {} }; class D { public: D(const C& c) {} }; class E { public: operator int() { // ... return 0; } }; int main() { //内置类型 <- 内置类型 int* p = nullptr; int i = (int)p; // 自定义类型 <- 内置类型 C c1 = 11; string s1 = "xxxx"; // 自定义类型 <- 自定义类型 D d = c1; list<int> lt; list<int>::const_iterator it = lt.begin(); // 内置类型 <- 自定义类型 E e; int x = e; cout << x << endl; return 0; }
2.3、【 IO流中的错误标志】
我们上面知道了istream在内部实现了类型转换使得cin返回的istream对象能够参与while循环的判断,但我们在看operate bool()时看到一个,其返回值与“错误标志”有关,那么我们来研究一下什么是错误标志:
共有以下错误标志:
说明一下:输入的数据类型必须与要提取的数据类型一致,否则出错。出错只是在流的状态字state中对应位置位(置1),程序继续。
那么我们思考一下,输入CTRL+C是终止进程,那为什么输入一个 CTRL+Z +回车,也可以正常退出呢?
通过下面四个接口可以看到每个错误标志的状态,哪个错误标志被设置了就会返回true.
int main() { cout << cin.good() << endl; cout << cin.eof() << endl; cout << cin.fail() << endl; cout << cin.bad() << endl <<endl; string str; //while (cin >> str) while (operator>>(cin, str).operator bool()) { cout << str << endl; } cout << cin.good() << endl; cout << cin.eof() << endl; cout << cin.fail() << endl; cout << cin.bad() << endl; return 0; }
通过这段代码可以看到在输入CRLT Z 的时候,eofbit failbit 标志被设置了。
并且如果错误标志被设置了,是不能接着提取数据的,程序也就正常退出了。如果还想在输入CTRL+Z+回车后,能让程序继续执行,继续能够提取我们的输入,就需要恢复这些错误标志,这里我们就可以调用clear 接口来实现:
图中的涉及所有知识点,有兴趣请自行前往学习:
【ios::clear - C++ 参考文档 --- ios::clear - C++ Reference】
现在我们使用clear重置以下错误标志:
int main() { cout << cin.good() << endl; cout << cin.eof() << endl; cout << cin.fail() << endl; cout << cin.bad() << endl << endl; string str; while (cin >> str) { cout << str << endl; } cout << endl << endl; cout << cin.good() << endl; cout << cin.eof() << endl; cout << cin.fail() << endl; cout << cin.bad() << endl; cin.clear(); cout << "clear后" << endl; cout << cin.good() << endl; cout << cin.eof() << endl; cout << cin.fail() << endl; cout << cin.bad() << endl; while (cin >> str) { cout << str << endl; } return 0; }
并且这里我们可以利用clear函数,自行设置错误标志,因此如果想让cin 不能用的话,我们可以自己设置结束标志:
int main() { cout << cin.good() << endl; cout << cin.eof() << endl; cout << cin.fail() << endl; cout << cin.bad() << endl << endl; string str; while (operator>>(cin, str).operator bool()) { if (str == "exit") { cin.clear(cin.failbit); break; } cout << str << endl; } return 0; }
为了能深刻理解“输入的数据类型必须与要提取的数据类型一致,否则出错。出错只是在流的状态字state中对应位置位(置1),程序继续”。下面还有一个场景:
这里就需要用到get函数,关于函数的具体内容请自行学习:
【iostream::get - C++ 参考文档 --- istream::get - C++ Reference】
这里我们简单看一下用法:
所以,这里我们可以写一个只能读取数字的程序:
int main() { int i; do { cin >> i; if (cin.fail()) { cin.clear(); char ch; cin.get(ch); } else { cout << i << endl; } } while (true); return 0; }
2.4、【getline函数】
我们要知道,空格和回车都可以作为数据之间的分隔符,所以多个数据可以在一行输入,也可以分行输入。但如果是字符型和字符串,则空格无法用cin输入,字符串中也不能有空格,回车符也无法读入。
例如,我们使用cin无法将含空格的字符串"hello world"输入到string对象中。#include <iostream> #include <string> using namespace std; int main() { string s; cin >> s; //输入:"hello world" cout << s << endl; //输出:"hello" return 0; }
结果:
所以对于含有空格的字符串,我们需要使用getline函数进行读取,因为getline函数只有遇到’\n’才会停止读取。
#include <iostream> #include <string> using namespace std; int main() { string s; getline(cin, s); //输入:"hello world" cout << s << endl; //输出:"hello world" return 0; }
结果:
2.5、【提高C++IO 效率】
在一些IO需求比较高的地方,比一些大量输入的计算题中,加上这三行代码,可以提高C++IO 效率。
int main() { cin.sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); return 0; }
由于C++ 是兼容C 的,所以IO流和C流就会有各自的缓冲区。默认情况下,IO流和C流是同步的。如果流是同步的,则程序可以将 iostream 操作与 stdio 操作混合使用,像下面这样:
int main() { int i, j; cin >> i; printf("%d\n", i); cin >> j; cout << j << endl; return 0; }
所以关闭流同步可以提高C++IO 效率。我们可以使用上面的3局代码,提高效率,使用nullptr的原因是,默认情况下,cin cout cerr是默认绑定的。我们给他一个nullptr 就会解除(cin cout)互相之间的绑定关系。
三、【C++文件IO流——<fstream>】
3.1、【文件操作步骤】
C++根据文件内容的数据格式将文件分为二进制文件和文本文件,采用文件流对象操作文件的一般步骤如下:
1、定义一个文件流对象,操作文件的类有以下三个:
2、使用文件流对象的成员函数打开一个磁盘文件,使得文件流对象和磁盘文件之间建立联系
文件,常见的打开方式如下:
3、使用提取和插入运算符对文件进行读写操作,或使用成员函数进行读写,对文件进行提取和插入操作的常用成员函数:
4、关闭文件,不需要用close,因为我们定义的文件流对象最终都会析构。
下面我们看一个例子:
#include<fstream> int main() { ofstream ofs;//ofstream ofs("test.txt");可以在构造的时候给文件名 ofs.open("test.txt",ofstream::out);//以写的方式打开 ofs.put('x'); ofs.write("hello\n", 6); ofs << "word" << endl; // 向文件中写入word(最好用) return 0; }
我们也可以将其读出来:
int main() { ifstream ifs("test.txt"); while (!ifs.eof()) { char c = ifs.get(); cout << c; } return 0; }
3.2、【以二进制的形式操作文件】
1、以二进制的形式对文件进行写入操作:
//以二进制的形式对文件进行写入 void WriteBinary() { ofstream ofile; //定义文件流对象 ofile.open("test.bin", ofstream::out | ofstream::binary); //以二进制写入的方式打开test.bin文件 char data[] = "20050202xzc"; ofile.write(data, strlen(data)); //将data字符串写入文件 ofile.put('!'); //将字符'!'写入文件 ofile.close(); //关闭文件 }
2、以二进制的形式对文件进行读取操作:
//以二进制的形式对文件进行读取 void ReadBinary() { ifstream ifile; //定义文件流对象 ifile.open("test.bin", ofstream::in | ofstream::binary); //以二进制读取的方式打开test.bin文件 ifile.seekg(0, ifile.end); //跳转到文件末尾 int length = ifile.tellg(); //获取当前字符在文件当中的位置,即文件的字符总数 ifile.seekg(0, ifile.beg); //重新回到文件开头 char data[100]; ifile.read(data, length); //将文件当中的数据全部读取到字符串data当中 //将文件中内容打印到屏幕上 data[length] = '\0'; printf("%s\n", data); ifile.close(); //关闭文件 }
操作如下:
//以二进制的形式对文件进行写入 void WriteBinary() { ofstream ofile; //定义文件流对象 ofile.open("test.bin", ofstream::out | ofstream::binary); //以二进制写入的方式打开test.bin文件 char data[] = "20050202xzc"; ofile.write(data, strlen(data)); //将data字符串写入文件 ofile.put('!'); //将字符'!'写入文件 ofile.close(); //关闭文件 } //以二进制的形式对文件进行读取 void ReadBinary() { ifstream ifile; //定义文件流对象 ifile.open("test.bin", ofstream::in | ofstream::binary); //以二进制读取的方式打开test.bin文件 ifile.seekg(0, ifile.end); //跳转到文件末尾 int length = ifile.tellg(); //获取当前字符在文件当中的位置,即文件的字符总数 ifile.seekg(0, ifile.beg); //重新回到文件开头 char data[100]; ifile.read(data, length); //将文件当中的数据全部读取到字符串data当中 //将文件中内容打印到屏幕上 data[length] = '\0'; printf("%s\n", data); ifile.close(); //关闭文件 } int main() { WriteBinary(); ReadBinary(); return 0; }
结果:
这里需要注意的是,当我们使用二进制读写,读写自定义类型,要注意自定义类型里是否存在容器,如果有容器,就要小心浅拷贝问题,所以最好不要用二进制读写容器。
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; } //ofs << winfo._date; ostream& operator << (ostream& out, const Date& d) { //out << d._year << "年" << d._month << "月" << d._day<<"日"; //out << d._year << "/" << d._month << "/" << d._day; out << d._year << " " << d._month << " " << d._day; return out; } struct ServerInfo { //char _address[32]; string _address; double _x; Date _date; }; // 写到文件 // 从文件读出来 // 1、二进制读写 // 2、文本读写 class BinIO { public: BinIO(const char* filename = "info.bin") :_filename(filename) {} void Write(const ServerInfo& winfo) { ofstream ofs(_filename, ofstream::out | ofstream::binary); ofs.write((char*)&winfo, sizeof(winfo)); } void Read(ServerInfo& rinfo) { ifstream ifs(_filename, ofstream::in | ofstream::binary); ifs.read((char*)&rinfo, sizeof(rinfo)); } private: string _filename; }; // //先写 //int main() //{ // ServerInfo winfo = { "192.0.0.0", 12.13, { 2022, 4, 10 } }; // BinIO bin; // bin.Write(winfo); // // return 0; //} // //再读 //int main() //{ // ServerInfo info; // BinIO bin; // bin.Read(info); // // cout << info._address << endl; // cout << info._x << endl; // cout << info._date << endl; // // return 0; //}
3.3、【以文本的形式操作文件】
与二进制相比,以文本的形式要简单得多,如下:
1、以文本的形式对文件进行写入操作:
//以文本的形式对文件进行写入 void WriteTxt() { ofstream ofile; //定义文件流对象 ofile.open("test.txt"); //以写入的方式打开test.txt文件 char data[] = "2005xzc"; ofile.write(data, strlen(data)); //将data字符串写入文件 ofile.put('!'); //将字符'!'写入文件 ofile.close(); //关闭文件 }
2、以文本的形式对文件进行读取操作:
//以文本的形式对文件进行读取 void ReadTxt() { ifstream ifile; //定义文件流对象 ifile.open("test.txt"); //以读取的方式打开test.txt文件 ifile.seekg(0, ifile.end); //跳转到文件末尾 int length = ifile.tellg(); //获取当前字符在文件当中的位置,即文件的字符总数 ifile.seekg(0, ifile.beg); //重新回到文件开头 char data[100]; ifile.read(data, length); //将文件当中的数据全部读取到字符串data当中 cout << length << endl; //将文件中内容打印到屏幕上 data[length] = '\0'; printf("%s\n", data); ifile.close(); //关闭文件 }
代码:
//以文本的形式对文件进行写入 void WriteTxt() { ofstream ofile; //定义文件流对象 ofile.open("test.txt"); //以写入的方式打开test.txt文件 char data[] = "2005xzc"; ofile.write(data, strlen(data)); //将data字符串写入文件 ofile.put('!'); //将字符'!'写入文件 ofile.close(); //关闭文件 } //以文本的形式对文件进行读取 void ReadTxt() { ifstream ifile; //定义文件流对象 ifile.open("test.txt"); //以读取的方式打开test.txt文件 ifile.seekg(0, ifile.end); //跳转到文件末尾 int length = ifile.tellg(); //获取当前字符在文件当中的位置,即文件的字符总数 ifile.seekg(0, ifile.beg); //重新回到文件开头 char data[100]; ifile.read(data, length); //将文件当中的数据全部读取到字符串data当中 cout << length << endl; //将文件中内容打印到屏幕上 data[length] = '\0'; printf("%s\n", data); ifile.close(); //关闭文件 } int main() { WriteTxt(); ReadTxt(); return 0; }
3.4、【使用>>和<<对文件进行操作】
使用>>和<<运算符对文件进行读写操作,会变得很简单,也很形象。
1、对文件进行写入操作://对文件进行写入操作 void WriteFile() { ofstream ofs("data.txt"); //定义文件流对象,并打开文件 ofs << "2005xzc!"; //字符串“流入”文件 ofs.close(); //关闭文件 }
2、对文件进行读取操作:
//对文件进行读取操作 void ReadFile() { ifstream ifs("data.txt"); //定义文件流对象,并打开文件 char data[100]; ifs >> data; //文件数据“流入”字符串data ifs.close(); //关闭文件 }
这里更好用方法是使用流插入和流提取来进行操作,下面我们使用自定义类型模拟一下:
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; } //ofs << winfo._date; ostream& operator << (ostream& out, const Date& d) { //out << d._year << "年" << d._month << "月" << d._day<<"日"; //out << d._year << "/" << d._month << "/" << d._day; out << d._year << " " << d._month << " " << d._day; return out; } struct ServerInfo { //char _address[32]; string _address; double _x; Date _date; }; // 2、文本读写 class TextIO { public: TextIO(const char* filename = "info.text") :_filename(filename) {} void Write(const ServerInfo& winfo) { ofstream ofs(_filename); ofs << winfo._address << endl; ofs << winfo._x << endl; ofs << winfo._date << endl; } void Read(ServerInfo& rinfo) { ifstream ifs(_filename); ifs >> rinfo._address; ifs >> rinfo._x; ifs >> rinfo._date; } private: string _filename; }; //先写 //int main() //{ // ServerInfo winfo = { "https://legacy.cplusplus.com/reference/fstream/ifstream/ifstream/", 12.13, { 2022, 4, 10 } }; // // TextIO text; // text.Write(winfo); // // //转字符串的方式 // // c // //double x = 1.111; // //char buff[128]; // //sprintf(buff, "%lf", x); // // // cpp // //to_string(x); // // return 0; //} 再读 int main() { ServerInfo info; TextIO text; text.Read(info); cout << info._address << endl;//我们可以直接使用流插入,流提取十分方便 cout << info._x << endl; cout << info._date << endl; return 0; }
注意:
- 使用ofstream类对象的open函数时,若不指定打开方式,则默认以写的方式打开文件;使用ifstream类对象的open函数时,若不指定打开方式,则默认以读的方式打开文件;使用fstream类对象的open函数时,若不指定打开方式,则默认以写+读的方式打开文件。
- 可以在定义文件流对象的同时指定将要打开的文件名,以及文件的打开方式。
四、【C++字符串IO流——<stringstream>】
4.1、【整数转字符串】
在C语言中,我们若是想要将一个整型变量的数据转化为字符串格式,有以下两种方法:
1、使用itoa函数进行转化。
int a = 10; char arr[10]; itoa(a, arr, 10); //将整型的a转化为十进制字符数字存储在字符串arr当中
2、使用sprintf函数进行转化。
int a = 10; char arr[10]; sprintf(arr, "%d", a); //将整型的a转化为字符串格式存储在字符串arr当中
虽然itoa函数和sprintf函数都能完成转化,但是在两个函数在转化时,都需要先给出保存结果的空间,而空间的大小是不太好界定的,除此之外,转化格式不匹配时,可能还会得到错误的结果甚至程序崩溃。
在C++中,我们可以使用stringstream类对象来避开此问题。在程序当中如果想要使用stringstream,必须要包含头文件sstream。在该头文件下,有三个类:
4.2、【stringstream】
这里主要介绍stringstream,stringstream主要可以用来:
1、将数值类型数据格式化为字符串。
#include <iostream> #include <sstream> #include <string> using namespace std; int main() { int a = 10; string sa; stringstream s; s << a; //将int类型的a放入输入流 s >> sa; //从s中抽取前面插入的int类型的值,赋值给string类型(方式一) cout << sa << endl; s.str(""); //将stringstream底层管理的string对象设置为""。 s.clear(); //将上次转换状态清空掉 //进行下一次转换 double b = 3.14; s << b; sa = s.str(); //获取stringstream中管理的string类型(方式二) cout << sa << endl; return 0; }
2、字符串拼接。
#include <iostream> #include <sstream> #include <string> using namespace std; int main() { string rets; stringstream s; s << "Fantasy" << "元前"; //将多个字符串放入stringstream中 s >> rets; //方式一获取 cout << rets << endl; s.str(""); //将stringstream底层管理的string对象设置为空字符串 s.clear(); //将上次转换状态清空掉 s << "Thanks" << " " << "for" << " " << "reading"; //将多个字符串放入stringstream中 rets = s.str(); //方式二获取 cout << rets << endl; return 0; }
下面看一个ostringstream和istringstream的例子:
int main() { int i = 100; Date d1 = { 2024, 9, 24 }; ostringstream oss; oss << i << endl << d1 << endl; string str; str = oss.str(); cout << str << endl; //istringstream iss(str); //istringstream iss; //iss.str(str); //istringstream iss("100 2024 9 24"); istringstream iss; iss.str("100 2024 9 24"); int i1; Date d2; iss >> i1 >> d2; return 0; }
3、序列化和反序列化结构数据
序列化是指将对象的状态转换为一种格式(通常是字节流或字符串),这种格式可以存储或传输。序列化后的数据通常称为序列化数据或序列化对象。反序列化是指将序列化后的数据(通常是字节流或字符串)转换回对象的状态。
#include <iostream> #include <sstream> #include <string> using namespace std; 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; } //ofs << winfo._date; ostream& operator << (ostream& out, const Date& d) { //out << d._year << "年" << d._month << "月" << d._day<<"日"; //out << d._year << "/" << d._month << "/" << d._day; out << d._year << " " << d._month << " " << d._day; return out; } struct ChatInfo { string _name; // 名字 int _id; // id Date _date; // 时间 string _msg; // 聊天信息 }; int main() { // 结构信息序列化为字符串 ChatInfo winfo = { "张三", 135246, { 2022, 4, 10 }, "晚上一起看电影吧" }; ostringstream oss; oss << winfo._name << " " << winfo._id << " " << winfo._date << " " << winfo._msg; string str = oss.str(); cout << str << endl << endl; // 我们通过网络这个字符串发送给对象,实际开发中,信息相对更复杂, // 一般会选用Json、xml等方式进行更好的支持 // 字符串解析成结构信息 ChatInfo rInfo; istringstream iss(str); iss >> rInfo._name >> rInfo._id >> rInfo._date >> rInfo._msg; cout << "-------------------------------------------------------" << endl; cout << "姓名:" << rInfo._name << "(" << rInfo._id << ") "; cout << rInfo._date << endl; cout << rInfo._name << ":>" << rInfo._msg << endl; cout << "-------------------------------------------------------" << endl; return 0; }
注意事项:
- stringstream实际是在底层维护了一个string类型的对象用来保存结果。
- stringstream在转换结尾时(即最后一个转换后),会将其内部状态设置为badbit,因此在下一次转换前必须调用clear将状态重置为goodbit才可以转换,但clear不会将stringstream底层的string对象清空。
- 可以使用s.str("")的方式将stringstream底层的string对象设置为空字符串,否则多次转换时,会将结果全部累积在底层string对象中。
- 获取stringstream转换后的结果有两个方法,一是使用>>运算符之间从流当中提取,二是使用s.str( )获取stringstream底层的string对象。
- stringstream使用string类对象代替字符数组,可以避免缓冲区溢出的危险,而且其会对参数类型进行推演,不需要格式化控制,也不会存在格式化失败的风险,因此使用更方便,更安全。
总结
本篇博客到这也就结束了,感谢你的观看!
.....................................................................................防备厚厚一本,是我献出自己的后遗症
————《木偶人》