【C++】I流

C language input and output

The most frequently used input and output methods in C language are scanf () and printf (). scanf(): Read data from the standard input device (keyboard) and store the value in a variable. printf(): Output the specified text/string to the standard output device (screen). Pay attention to the width output and precision output controls. C language uses corresponding buffers for input and output. As shown below:

What is flow?

"Flow" means flow. It is the process of material flowing from one place to another. It is an abstract description of an orderly, continuous and directional data (the unit can be bit, byte, packet). C++ flow refers to the process of inputting information from an external input device (such as a keyboard) to the inside of a computer (such as a memory) and outputting information from the memory to an external output device (a monitor). This input-output process is vividly compared to "flow". Its characteristics are: orderly, continuous and directional.

In order to realize this flow, C++ defines an I/O standard class library. Each of these classes is called a stream/stream class to complete a certain function.

C++IO流

C++ provides four global stream objects cin, cout, cerr, clog.

cin: read data.

cout: output data.

cerr: Output error.

clog: output log.

cin and cout can directly input and output built-in type data, because the standard library has overloaded the input and output of all built-in types. If you want to output a custom type, you only need to overload and in the operator <<class operator>>.

Loop to read data

// 单个元素循环输入
while(cin>>a)
{
    
    
    // ...
}
// 多个元素循环输入
while(cin>>c>>a>>b>>c)
{
    
    
    // ...
}
// 整行接收
while(cin>>str)
{
    
    
    // ...
}

Under the VS compiler: Ctrl+Z can end the loop reading.

while(cin>>a), what is called here is the object operator >>whose return value is istreamtype, and then while()the loop will judge whether the return value is true or false, so it will be called again operator bool.

When you enter Crtl+Z, it is falsetime to return.

#include<iostream>
using namespace std;

class Date
{
    
    
	friend istream& operator>>(istream& in, Date& d1);
	friend ostream& operator<<(ostream & out, Date& d1);
public:
	Date(int year = 2023, int month = 8, int days = 17)
		:_year(year)
		, _month(month)
		, _days(days)
	{
    
    }

	operator bool()
	{
    
    
		if (_year == 0) return false;//随便写的
		else return true;
	}

private:
	int _year;
	int _month;
	int _days;
};

istream& operator>>(istream& in, Date& d1)
{
    
    
	return in >> d1._year >> d1._month >> d1._days;
}

ostream& operator<<(ostream & out, Date& d1)
{
    
    
	return out << d1._year << d1._month << d1._days;
}

int main(void)
{
    
    
	Date d1(0, 1, 1);
	while (d1)
	{
    
    
		cout << "while(d1)" << endl;
	}
	cout << "false" << endl;
	return 0;
}

===============================================
	输出结果为: false

C++ file IO stream

Read and write files

struct ServeInfo
{
    
    
	char _address[32];
	int _port;
};

class ConfigManager
{
    
    
public:
	ConfigManager(const char* filename)
		:_filename(filename)
	{
    
    }

	void WriteBin(const ServeInfo& info)
	{
    
    
		ofstream ofs(_filename, ios_base::out | ios_base::binary);
		ofs.write((const char*)&info, sizeof(info));
		//ofs << info._address <<endl<< info._port << endl;
	}

	void ReadBin(ServeInfo& info)
	{
    
    
		ifstream ifs(_filename, ios_base::in | ios_base::binary);
		ifs.read((char*)&info, sizeof(info));
        //ifs >> info._address >> info._port>>info._date;
	}

private:
	string _filename;
};

int main(void)
{
    
    
	ServeInfo winfo= {
    
     "192,168.1.1", 8888 };//初始化信息
	ConfigManager cf_bin("test.txt");//传递文件地址
	cf_bin.WriteBin(winfo);//传递信息,写入文件

	ServeInfo rbinfo;
	cf_bin.ReadBin(rbinfo);//打印文件内容
	cout << rbinfo._address << " " << rbinfo._port << " " << endl;
	return 0;
}

stringstream

Convert all to string

Convert numeric type data format to string

	int a = 12345678910;
	string sa;
	stringstream s;
	s << a;
	s >> sa;
	cout << typeid(s).name() << endl;
	// clear()
	// 注意多次转换时,必须使用clear将上次转换状态清空掉
	// stringstreams在转换结尾时(即最后一个转换后),会将其内部状态设置为badbit
	// 因此下一次转换是必须调用clear()将状态重置为goodbit才可以转换
	// 但是clear()不会将stringstreams底层字符串清空掉

	// s.str("");
	// 将stringstream底层管理string对象设置成"", 
	// 否则多次转换时,会将结果全部累积在底层string对象中

	s.str("");
	s.clear();
 clear()
 注意多次转换时,必须使用clear将上次转换状态清空掉
 stringstreams在转换结尾时(即最后一个转换后),会将其内部状态设置为badbit
 因此下一次转换是必须调用clear()将状态重置为goodbit才可以转换
 但是clear()不会将stringstreams底层字符串清空掉

 s.str("");
 将stringstream底层管理string对象设置成"", 
 否则多次转换时,会将结果全部累积在底层string对象中

String concatenation

	stringstream sstream;

	sstream << "first" << " " << "string";
	sstream << " second string";
	cout << "strResult:  " << sstream.str() << endl;

Serialize and deserialize structured data

	ServeInfo info= {
    
     "123.123.123.123",80 };
	ostringstream oss;
	oss << info._address << "  " << info._port << endl;
	string str = oss.str();
	cout << str << endl;

	ServeInfo rinfo;
	istringstream iss(str);
	iss >> rinfo._address >> rinfo._port;
	cout << "==========================================" << endl;
	cout << rinfo._address << " " << rinfo._port << endl;
  1. Stringstream actually maintains a string type object at its bottom layer to save the results.
  2. When converting data types multiple times, you must use clear() to clear them to achieve correct conversion, but clear() will not clear the underlying string object of stringstream.
  3. The underlying string object can be set to the "" empty string using the s.str("") method.
  4. You can use s.str() to have stringstream return its underlying string object.
  5. Stringstream uses string class objects instead of character arrays, which can avoid the risk of buffer overflow, and it will deduce parameter types without formatting control and without the risk of formatting failure, so it is more convenient and safer to use.

Guess you like

Origin blog.csdn.net/AkieMo/article/details/132350194