Learning STL (10): input and output streams

  • Stdio stream
  • File input and output streams
  • String input and output streams

Stdio stream

I.e., the standard input stream cin, the standard output stream cout. The former refers to the keyboard, which refers to the display.

1 and extracted caret symbol

The input and output stream class library, two overloaded operators to simplify the use of the input and output streams, operator << caret used to do input and output streams, indicating "to output", e.g. cout << "Hello" is the string "Hello" to the screen; operator >> often used for extracting symbol indicating "is assigned to", e.g. cin >> i is assigned to the input information from the keyboard to the i.

Standard input to the lack of examples of different types of variable assignment.

#include <iostream>
using namespace std;
int main() {
	int i;
	char str[20];
	cout << "请输入一个整形数及一个字符串:" ;
	cin >> i >> str;
	cout << "i=" << i << endl ;
	cout << "str=" << str << endl ;
	return 0;
}

If you enter on the command line 1 how are you ?, the results after the carriage return is:

请输入一个整形数及一个字符串:1 how are you?
i=1
str=how

In fact in the interactive process, often requires one line of input character sequence, scanning and conversion work when these characters are safely stored into a buffer before. In this example, the string can not enter fully into memory, the following get mentioned family of functions a good solution to this problem.

2 get family of functions  

There are three commonly used functions.

(1) int get (); Returns a stream input character ASCII value.

(2)istream& get(unsigned char* pszBuf, int nBufLen, char   delim=’\n’);     

pszBuf: pointer to the character buffer for holding the results nBufLen: buffer length delim: end character, the character is determined according to the end when the reading operation is stopped

(3) istream & getline (unsigned char * pszBuf, int nBufLen, char delim = '\ n'); get the same of parameters

The first two functions get and getline functions are read his record, then they have what difference does it make? Subtle but important difference is: when encountering delimiters (the delim, i.e. the end of the character) in the input stream get () execution, but is not extracted from the input stream delimiters, ending directly in a string buffer added to the tail flag '\ 0'; function getline () on the contrary, it extracts from the input stream delimiters, but still does not store it in the results buffer. 

#include <iostream>
using namespace std;
int main() {
	char szBuf[60]; //定义输入字符串接收缓冲区
	cout << "请输入一个字符串:" ;
	int n = cin.get();  //先读1个字符
	cin.getline(szBuf, 60); //接着读1行字符,遇到结束符’\0’停止
    cout << n << endl;
    cout << "The received string is: " << szBuf << endl;
    return 0;
}
//输出结果
请输入一个字符串:abcde
97
The received string is: bcde

3 processing flow error  

Obtain status information of the function is as follows:

  • int rdstate (); no arguments, return values ​​eigenvalue only status information. Use the following function to detect the respective input / output status:
  • bool good (); if the return value is true, everything is normal, no error has occurred.
  • bool eof (); Return Value if true, indicates that the end of the stream has been reached.
  • bool fail (); Return Value if true, it indicates that I / O operation failed, mainly because illegal data (e.g. numbers encountered when reading letters). But the flow can continue to use.
  • bool bad (); occurred (perhaps physical) fatal error, the flow will not continue to use.
//判断是否输入整形数。
int main() { 
	int a;
	cout << "请输入一个数据: ";
	cin>>a;
	cout<<"状态值为: " <<cin.rdstate()<<endl;
	if(cin.good())
	{
		cout<<"输入数据的类型正确,无错误!"<<endl;
	}
	if(cin.fail())
	{
		cout<<"输入数据类型错误,非致命错误,可清除输入缓冲区挽回!"<<endl;
	}
	return 0;
}

//确保输入一个整形数给变量a。
int main() { 
	int a;
	while(1)
	{
	cin>>a;			//赋值给整形数a
	if(cin.fail())	//如果输入数据非法,则:
	{
		cout<<"输入有错!请重新输入"<<endl;
		cin.clear();//清空状态标识位
		cin.get();	//清空流缓冲区
	}
	else			//如果输入数据合法,则:
	{
		cout<<a<< endl;    //直接在屏幕上输出数据
		break;		//跳出while循环
	}
      }
return 0;
}

2 file input and output streams

Used to read and write files are C ++ ifstream, ofstream and fstream stream class, the same is in accordance with "Open -> write -> Close" primitive operation. Many constants are used to read and write files are defined in the base class out in ios. ifstream class only used to read file data, ofstream class only for writing data to a file, fstream data can be written to the file and for reading.

1 File Open

ifstream / ofstream / fstream stream class using a constructor function to open or open a file, the following prototype: 

ifstream( const char* szName, int nMode = ios::in, int nProt = filebuf::openprot )

ofstream( const char* szName, int nMode = ios::out, int nProt = filebuf::openprot )

fstream( const char* szName, int nMode, int nProt = filebuf::openprot );

void ifstream::open(const char *filename, int openmode=ios::in)

void ofstream::open(const char *filename, int openmode=ios::out|ios::trunc)

void fstream::open(const char *filename, int openmode=ios::in|ios::out)

Has two parameters, the first one is the file name, the second way is to open, see below Open:  

  • ios :: in Open file for reading
  • ios :: out Open file for writing
  • ios :: app every time data is written, the file pointer to the first end of the file, to append data to the end
  • Ios :: ate only when the initial end of the file pointer to the file, the data can still be written in an arbitrary position
  • ios :: trunc before writing data, delete the original file contents (empty file), when the file does not exist creates the file
  • ios :: binary open the file in binary mode, without any character conversion

2 file is closed

ifstream / ofstream / fstream stream classes are close by releasing the file resource function. close (); no parameters, open the file and closing the file generally appear in pairs.

3 file read and write

//读文本文件并显示在屏幕上
int main(){
	char szBuf[80];
	ifstream in("a.txt");//通过构造函数创建文件读入流
	if(!in) return 0;		//若文件不存在,返回
	while(in.getline(szBuf, 80)) //通过getline函数按行读取内容
	{
	cout << szBuf << endl;	//将读入缓冲区内容输出到屏幕上,判断是否正确
	}
	
	in.close();
	return 0;
}

//写文本文件:把学生成绩信息保存至文件
struct STUDENT	//学生成绩结构体
{
	char strName[20];	//姓名
	int  nGrade;		//成绩
};
int main() {
	ofstream out;
	out.open("d:\\a.txt");	//打开或创建a.txt文本文件
	STUDENT st1 ={"张三", 90};//用结构体产生两名学生的成绩信息
	STUDENT st2 ={"李四", 80};
	out << st1.strName << "\t" << st1.nGrade << endl;//把成绩信息存到文本文件
	out << st2.strName << "\t" << st2.nGrade << endl;
	out.close();
	return 0;
} 

As can be seen, the "<<" text file is written to complete a preferred method, this is because the "<<" operator to direct the output of different types of data. In strName structure is a string, nGrade are integers, but may be output directly to the file. Further use and between strName nGrade "\ t" is output for data alignment, and "endl" guaranteed output "\ n" carriage return, line feed to ensure that the text file is necessary.

Reading and writing binary files

Mainly through the read (), write () function to read and write binary function prototypes as follows

  • ostream& write(const char *, int nSize)
  • istream& read(char *, int nSize)

The first parameter indicates the read pointer to the first buffer, the second parameter indicates the read buffer size

//写二进制文件:把学生成绩信息保存至文。
struct STUDENT	//学生成绩结构体
{
	char strName[20];	//姓名
	int  nGrade;		//成绩
};
int main() {
	ofstream out;
	out.open("d:\\a.txt");	//打开或创建a.txt文本文件
	STUDENT st1 ={"张三", 90};//用结构体产生两名学生的成绩信息
	STUDENT st2 ={"李四", 80};
	out.write((const char *)&st1, sizeof(STUDENT));	//把成绩信息存到二进制 文件
	out.write((const char *)&st2, sizeof(STUDENT));
	out.close();
	return 0;
}

//读二进制文件,并把结果显示在屏幕上。
int main() {
	ifstream in;
	in.open("d:\\a.txt");
	if(!in) return 0;
	STUDENT st1;
	STUDENT st2;
	in.read((char *)&st1, sizeof(STUDENT));
	in.read((char *)&st2, sizeof(STUDENT));
	cout << st1.strName << "\t" << st1.nGrade << endl;
	cout << st2.strName << "\t" << st2.nGrade << endl;
	in.close();
	return 0;
} 

Input and output buffer stream

C ++ Standard Library class encapsulates a buffer streambuf, input and output stream object for use. Each C ++ standard input and output stream object contains a pointer pointing to streambuf, the user can () member function to obtain the pointer by calling rdbuf, so as to directly access the underlying streambuf object, can read and write data directly to the underlying buffer, thereby skipping formatting the upper input and output operations. However, due to similar functions can be realized by the upper buffer classes, so we no longer be discussed. The best part is that it streambuf overloaded operator << and operator >>. For operator <<, it streambuf pointer to parameters, and the output of all the characters to an output object streambuf flowing out; for operator >>, it may be subject to all the characters in the input stream is input to streambuf object.

//打开一个文件并把文件中的内容送到标准输出中。
int main() {
    ifstream fin("d:\\my.txt");
	if(fin !=NULL)			//判断文件是否存在
	{
		cout<<fin.rdbuf();  //把文件所有内容输出到屏幕上
	}
	fin.close();	
}

Positioning input and output streams

Location identifier has three flow:

  • Starting position ios :: beg stream
  • ios :: cur current position of the stream
  • ios :: end position location function end there are two main streams:

istream& seekg(long relativepos, ios::seek_dir dir)

For input stream. The first parameter is the number of characters to be moved, either positive or negative; the second parameter is the direction of movement, is ios :: begin, ios :: cur, ios :: a value in the end. Meaning: character pointer with respect to the moving direction of the forward or backward a number of characters.

ostream & seekp (long relativepos, ios :: seek_dir dir) for the output stream. Parameter Meaning with seekg.

//下面示例先写文件,然后再把文件内容读出显示在屏幕上。
int main() {
	fstream	in_out;
	in_out.open("d:\\my.txt",ios::in|ios::out|ios::trunc);
	in_out.write("Hello", 5);
	in_out.seekg(0, ios::beg);  //读指针移到文件头
	cout << in_out.rdbuf();
	in_out.close();
	return 0;
}

String input and output streams 3

The library defines three types of flow string.

  • stringstream input stream, providing a read function string
  • ostringstream output streams, provide write string function
  • stringstream input and output stream, string write function
//反解字符串给各变量赋值
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
	int n;
	float f;
	string strHello;
	string strText = "1 3.14 hello";
	istringstream s(strText);
	s >> n;
	s >> f;
	s >> strHello;
	cout << "n= " << n << endl;
	cout << "f= " << f << endl;
	cout << "strHello= " << strHello << endl;
	return 0;
}
//合并不同类型的数据到字符串
int main()
{
	cout << "type an int,a float and a string: ";
	int i;
	float f;
	string stuff;
	cin >> i >> f;
	getline(cin, stuff);
	ostringstream	os;
	os << "integer= " << i << endl;
	os << "float= " << f << endl;
	os << "string= " << stuff << endl;
	string result = os.str();
	cout << result << endl;
	return 0;
}

Comprehensive example

#include <iostream>
#include <string>
using namespace std;

class Student
{
public:
	string strName;		//姓名
	string strSex;		//性别
	int	   nAge;		//年龄
};
istream& operator>> (istream& is, Student& s)
{
	is >> s.strName >> s.strSex >> s.nAge;
	return is;
}
ostream& operator << (ostream& os, Student& s)		//Student是普通对象
{
	os << s.strName << "\t" << s.strSex << "\t" << s.nAge << "\n";
	return os;
}
ostream& operator << (ostream& os, const Student& s)//Student是常对象
{
	cout << "const Student输出是:" << endl;
	os << s.strName << "\t" << s.strSex << "\t" << s.nAge << "\n";
	return os;
}
void f(const Student& s)
{
	cout << s;
}
int main(int argc, char *argv[])
{
	Student s;
	cout << "请输入数据(姓名 性别 年龄):";
	cin >> s;
	cout << "输入的数据是: ";
	cout << s;
	f(s);    
	return 0;
}	

 

The main emphasis of the program appreciated cin >> s, cout << usage s, which are the object of the operation. When cin >> s, in fact, the real call is overloaded istream & operator >> (istream & is, Student & s), how to enter the function body is done; empathy when cout << s, is the real calling overloaded ostream & operator << (ostream & os, Student & s), how the output is done by the function thereof; when the Student is often object, such as the function void f (const Student & s) in cout << s call is ostream & operator << (ostream & os, const Student & s). So why the basic data types do not have to reload the corresponding function? That is because the default STL to achieve the basic data types of input and output functions, we would not be necessary again overloaded.

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/QQ2558030393/article/details/93396285