There are three main types of IO: standard input and output, file input and output, and string stream. All two of the following are inherited from the first standard input and output. The respective header files they correspond to are:
Standard input/output: #include <iostream>
File input/output: #include <fstream>
String Flow: #include <sstream>
Stream objects cannot be copied and duplicated. So the stream object cannot be used for assignment and parameter passing, and if it must be passed, a pointer or reference must be passed.
Here is an example of the use of a Stream object, which illustrates the state of the Stream object's properties. On the code, if the local D packing directory has a file hello.txt. The content in the file is 001--006.
1#include"stdafx.h"2#include <fstream>3#include <sstream>4#include <iostream>5 6 using namespacestd;7 8 9Ifstream &print (Ifstream &inch)Ten { One stringstr; A -cout <<inch. Bad () <<Endl; -cout <<inch. Good () <<Endl; thecout <<inch. Fail () <<Endl; -cout <<inch. EOF () <<Endl; -cout <<"--------------------1"<<Endl; - while(inch>>str) + { -cout << str <<Endl; + } Acout <<"--------------------2"<<Endl; atcout <<inch. Bad () <<Endl; -cout <<inch. Good () <<Endl; -cout <<inch. Fail () <<Endl; -cout <<inch. EOF () <<Endl; -cout <<"--------------------3"<<Endl; - inch. Clear (); incout <<inch. Bad () <<Endl; -cout <<inch. Good () <<Endl; tocout <<inch. Fail () <<Endl; +cout <<inch. EOF () <<Endl; - inch. SEEKG (0, Ios_base::beg); the return inch; * } $ Panax Notoginseng intMain () - { theIfstreaminch("D://hello.txt"); + stringstr; APrintinch); the while(inch>>str) + { -cout << str <<Endl; $ } $ inch. Close (); - return 0; -}
As the code example above reads a file and prints the contents of the file to the console, resets the IO stream and re-prints it again.
Where the following code represents the four states of a Stream object:
In.bad () returns true if the stream is corrupted.
In.good () returns true if the stream is in a valid state.
In.fail () returns True if the IO operation fails.
In.eof () returns True if the file is read to the end of the file.
in. Clear (); Used to reset all states.
IN.SEEKG (0, Ios_base::beg); Resets the pointer to the file operation at the beginning of the file.
C + + IO Learning