C + + STL Fundamentals and Applications (4) output output stream

Source: Internet
Author: User
Tags sin

A set of template classes are provided in the standard Template Library of C + + to support the input and output functions of object-oriented data, such as basic input and output streams IStream class/ostream class, file input and output stream Ifstream class/ofstream class/fstream class, string input output stream StringStream Class/istringstream class/ostringstream class and so on. C + + I/O can also perform input and output operations on objects that are not available in C. These flows are located in the noun space STD, which is usually the suffix of stream. They are flexible, perfect and powerful in the processing of data streams.

This chapter describes the use of standard input and output streams, file input and output streams, and string input and output streams. the inheritance relationship between the flow classes

Needless to say, everything is clear.


Figure one: The inheritance relationship between the flow classes

and give the necessary definitions:

typedef Basic_ios<char, char_traits<char> > iOS;
typedef Basic_streambuf<char, char_traits<char> > Streambuf;
typedef Basic_istream<char, char_traits<char> > IStream;
typedef Basic_ostream<char, char_traits<char> > ostream;
typedef Basic_iostream<char, char_traits<char> > iostream;
typedef Basic_stringbuf<char, char_traits<char>,allocator<char> > stringbuf;
typedef Basic_istringstream<char, char_traits<char>,allocator<char> > Istringstream;
typedef Basic_ostringstream<char, char_traits<char>,allocator<char> > Ostringstream;
typedef Basic_stringstream<char, char_traits<char>,allocator<char> > StringStream;
typedef Basic_filebuf<char, char_traits<char> > filebuf;
typedef Basic_ifstream<char, char_traits<char> > Ifstream;
typedef Basic_ofstream<char, char_traits<char> > Ofstream;
typedef Basic_fstream<char, char_traits<char> > fstream;

After you have an overview of the relationship between flow classes, enter the text.

standard input/output streamstandard input stream cin (i.e. keyboard), standard output stream cout (i.e. display).

caret << with extract >>The two operators operator << and operator >> are overloaded in the input and output stream libraries (that is, <istream> and <ostream>), and are used to simplify the use of input and output streams. "<<" is commonly used as a caret, indicating "output to", such as cout<< "Hello" to Output "hello" to the screen. ">>" is commonly used as an extract, indicating "Assign to", for example, Cin>>i is to assign the keyboard input information to I.

Why can I use CIN and cout directly? VC + + compiled console program on Windows, actually do not start from main, but start from mainCRTStartup (), perform some initialization action and then call the main function, these initialization actions include initialization of CIN and cout, So the CIN, cout object was created at the time of the CRT initialization, and before main (),
Using CIN to get input and use cout to output to the screen, in fact CIN and cout inside are called WINDOWSAPI, such as Readconsole () and writeconsole () to achieve the acquisition of user input and output to the screen, And the API is how to manipulate the device (monitor) display text, this is the Windows system thing. Of course, this is the case on Windows, where the internal invocation of CIN and cout on Linux or other systems is the corresponding Linux API and so on.

In <iostream>, you can see that cin,cout is a global variable with the following statement.
extern IStream cin;
extern ostream cout;

example of standard input and output stream code:

#include <iostream>using namespace Std;int main () {    int i;    float F;    Char s[20];    cin>>i;    cin>>f;    cin>>s;    cout<< "i=" <<i<<endl;    cout<< "f=" <<f<<endl;    cout<< "s=" <<s<<endl;    return 0;}
where the caret "<<" and the Extract ">>" are used consecutively. For CIN, the data is separated by a space by default and can be assigned using Cin>>i>>f>>s in the program above, using cout<< "i=" <<i<<endl< < "f=" <<f<<endl<< "s=" <<s<<endl to output.

since CIN is separated by a space by default, how to read a single line of string such as "How is?" It? The Get Series function solves this problem very well. There are three common get series functions, as follows:

(1) Get ();
Reads the ASCII value of the first character of the input stream.
(2) istream& get (unsigned char * pszbuf,int nbuflen,char delim= ' \ n ');
PSZBUF: A pointer to a string buffer that holds the read result.
Nbuflen: Specifies the buffer size.
Delim: Specifies the delimiter, which is not filled, at which time the default is ' \ n '.
(3) istream& getline (unsigned char * pszbuf,int nbuflen,char delim= ' \ n ');
The parameter interpretation is the same as (2), except that (2) when the delimiter is encountered, it stops executing, the delimiter is not read, and (3) The delimiter is read, but it is not stored in the result cache.

Take a closer look at the differences between the following two sections of code, compare the results, and experience the difference between (2) and (3).

#include <iostream>using namespace Std;int main () {char s1[100],s2[100];cout<< "input:? How is it? (Tab key) Fine,thank you! " <<endl;int a=cin.get (); Cin.get (s1,sizeof (S1), ' \ t '), Cin.getline (s2,sizeof (S2), ' \ n ');cout<< "A:" < <a<<endl<< "S1:" <<s1<<endl<< "S2:" <<s2<<endl;return 0;}
Attention! Only the Get () and getline () positions are changed. #include <iostream>using namespace Std;int main () {char s1[100],s2[100];cout<< "input:? How is it? (Tab key) Fine,thank you! " <<endl;int a=cin.get (); Cin.getline (s1,sizeof (S1), ' \ t '), Cin.get (s2,sizeof (S2), ' \ n ');cout<< "A:" < <a<<endl<< "S1:" <<s1<<endl<< "S2:" <<s2<<endl;return 0;}
the first piece of code executes the result:
63
How is it?
Fine,thank you!
(Note that tabs were output before Fine)

The second piece of code executes the result:
63
How is it?
Fine,thank you!

Because '? ' The ASCII value is 63, so first output 63, the second paragraph has no output tab is the reason that getline () extracted the tab, but did not deposit the result buffer.

Handling Stream ErrorsHow can I tell if the input and output operation has an error? C + + has recorded its status information for each input and output operation, stored in the variable int _mystate, which can be used to determine whether the input and output operation is correct or not.

The functions to get state information are as follows:
int rdstate (); No parameters, return _mystate, through the following four functions to determine the input and output operation status.

Use the following four functions to detect the corresponding state:
BOOL Good () const//input correct
{ Test if no state bits is set
Return (rdstate () = = Goodbit);
}

BOOL EOF () const//reached end of stream
{ Test if Eofbit is set on stream state
return ((int) rdstate () & (int) eofbit);
}

the bool Fail () const//I/O failed mainly due to illegal data, but the stream can continue to be used
{ Test if Badbit or Failbit is a set in stream state
Return (((int) rdstate () & ((int) badbit | (int) failbit))! = 0);
}

BOOL Bad () const//Fatal error (perhaps physical), stream cannot continue to use
{ Test if Badbit is set on stream state
Return (((int) rdstate () & (int) badbit)! = 0);
}
Where the flags are as follows:
static const _iostate Goodbit = (_iostate) 0x0;
static const _iostate Eofbit = (_iostate) 0x1;
static const _iostate Failbit = (_iostate) 0x2;
static const _iostate Badbit = (_iostate) 0x4;the function code to detect a stream error is as follows:
#include <iostream>using namespace Std;int main () {int a;cin>>a;cout<< "Enter the status information code:" << Cin.rdstate () <<endl;if (cin.eof ()) {cout<< "reached the end of the stream!" <<endl;} Else{if (Cin.good ()) {cout<< "input correct!" <<endl;} if (Cin.fail ()) {cout<< "input data type Error!" <<endl;} if (Cin.bad ()) {cout<< "Fatal error!" <<endl;}} return 0;}
Input: 1
Output: Input status information code: 0 input Correct!

Input: A
Output: Input status information code: 2 input data type Error!

Input: Ctrl key +z (Ctrl+d under Linux)
Output: Enter the status information code: 3 has reached the end of the stream!

Note that the last case uses CTRL + Z to make the console simulate a file terminator, which is typically used by EOF () when reading a file to determine if it has been read.

In addition, when generating a cin.fail () error, you can continue to use the stream by clearing the current buffer, using the cin.clear () function to clear the status flag bit, and using get () to read the wrong data to discard to reuse the stream, as shown below.
#include <iostream>using namespace Std;int main () {int d[5];int n=0;while (n<5) {cin>>d[n];if (Cin.fail () ) {cout<< "Data type Error! Discard the data and Continue reading!" <<endl;cin.clear ();    Clear status Flag bit cin.get ();    Read this error data out of the stream to discard the}else{cout<< "read before" <<n+1<< "digits:"; for (int i=0;i<=n;i++) cout<<d[i]; cout<<endl;n++;}} return 0;}
Input:
1 a 2 B 3 4 5
Output:
The first 1 digits have been read correctly: 1
Data type Error! Discard the data and Continue reading!
The first 2 digits have been read correctly: 12
Data type Error! Discard the data and Continue reading!
The first 3 digits have been read correctly: 123
The first 4 digits have been read correctly: 1234
The first 5 digits have been read correctly: 12345

file input/output streamC + + uses the Ifstream, Ofstream, and FStream stream classes for file reads and writes, as well as with the "open, read-write, and close" primitives. Many of the constants used to read and write files are defined in the base class iOS, the Iftream class is used only to read file data, the Ofstream class is used only to write data to a file, and the FStream class can be used to read and write file data.

File OpenThe ifstream, Ofstream, and FStream stream classes use constructors or the open () function for opening a file with the following prototype:
Ifstream (const char* Szname,int nmode=ios::in,int nprot= (int) ios_base::_openprot)
Ofstream (const char* Szname,int nmode=ios::out,int nprot= (int) ios_base::_openprot)
FStream (const char* szname,int nmode,int nprot= (int) ios_base::_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)

SzName: File name
Nmode: Open With the following methods:
Ios::in     Open file as read.
Ios:out     Open file in write mode.
Ios:app     Each time the data is written, the file pointer is moved to the end of the file to append the data to the tail.
Ios:ate     Only initially moves the file pointer to the end of the file, and throws to write the data anywhere.
Ios:trunc     Before writing the data, delete the original file contents (empty the file) and create a file when the file does not exist.
Ios:binary     Opens the file in binary form.

Nprot: Specifies the File Protection specification, default to (int) Ios_base::_openprot, which is the operating system default, which refers to compatible sharing mode.

file CloseThe ifstream, Ofstream, FStream stream classes use the close () function to release file resources.
Close () has no parameters, in general, open files and closed files are paired.

file read/write

1. Read and write text files

text files are the most common operand, and the key is to solve the problem of how to read by line and how to write by line.
After executing the program, a "test.txt" file can be generated in the current directory of the executable file.
#include <iostream> #include <fstream>using namespace Std;int main () {char s[100];ofstream fout ("Test.txt") ;fout<< "Hello world!" <<endl<< "How is it?" <<endl<< "Fine,thank you!"; Fout.close (); Ifstream fin ("test.txt"); if (!fin) {cout<< "file does not exist!"; return 0;} Else{while (!fin.eof ()) {Fin.getline (s,sizeof (s)); Cout<<s<<endl;}} return 0;}

2. Read and write binary files

binary file reads and writes are often used, using the following function to read and write binary files.
ostream& Write (const char*,int nSize)
istream& Read (Char*,int nSize)

Read and write the binary file code as follows:
(The executable file produces a "Test.txt file", right-click on the property to find the file size of 24 bytes, that is, the size of the structure STUDENT)
#include <iostream> #include <fstream>using namespace std;struct student{char name[20];int ID;}; int main () {STUDENT t1={"Zhang San", 15}; STUDENT t2;ofstream fout ("test.txt"); Fout.write ((const char*) &t1,sizeof (t1)); Fout.close (); Ifstream Fin (" Test.txt "); if (!fin) {cout<<" File open failed! "; return 0;} Else{fin.read ((char*) &t2,sizeof (T2)); Cout<<t2.name<<endl<<t2.id;fin.close ();} return 0;}

3. Input/output stream buffering

The C + + standard library encapsulates a buffer class steambuf for use by input and output stream objects. Each standard C + + input and output stream object contains a pointer to a carton streambuf that the user can obtain by calling the Rdbuf () member function to gain direct access to the underlying Streambuf object, which can be read and written directly to the underlying buffer. This skips the formatting input and output operations of the upper layer. But because similar functions can be implemented by the upper buffer, it is not discussed. The most exciting part of STREAMBUF is that it overloads the operator<< and operator>>. For operator<<, it takes the Streambuf pointer as the parameter to output all the characters in the Streambuf object to the output stream; for operator>>, all the characters in the input stream object can be output to The Streambuf object.

Open a file and send the contents of the file to the standard output stream:
#include <iostream> #include <fstream>using namespace Std;int main () {ifstream fin ("test.txt"), if (Fin) { Cout<<fin.rdbuf ();} Fin.close (); return 0;}
The same is the output of the file content, this method is very concise. Of course, if the cout<<fin.rdbuf () to the left of the standard output stream to the file output stream, you can implement the function of the file assignment.

4. Positioning the input/output stream

The position of a stream is identified by three:
Start position of the Ios::beg stream
Current position of the Ios::cur stream
End position of the Ios::end stream

There are two main positioning functions
istream& seekg (Long Relativepos,ios::seek_dir dir)
For an input stream, the first parameter is the number of characters to move, can be positive, and the second parameter is the direction of movement, which is a value in the position identification of the stream above. The meaning is how many characters the character pointer moves forward or backward relative to the direction of movement.
ostream& seekp (Long Relativepos,ios::seek_dir dir)
For output stream, meaning same as istream& seekg (Long Relativepos,ios::seek_dir dir)
In addition, when the above two functions pass only one argument, the absolute position that is moved to the stream, such as SEEKG (4), indicates the fourth character position to move to the stream.

The location function uses the following code:
#include <iostream> #include <fstream>using namespace Std;int main () {fstream fout ("Test.txt", Ios::in|ios: : Out|ios::trunc); Fout.write ("How is You?"); Fout.seekp (0,ios::beg)    ; Move the pointer to the file header Cout<<fout.rdbuf () <<ENDL;FOUT.SEEKP (4);    Move the pointer to position fourth of the stream Cout<<fout.rdbuf () <<ENDL;FOUT.SEEKP (0,ios::end);    Move the pointer to the end of the file Cout<<fout.rdbuf (); Fout.close (); return 0;}
output:
How is it?
Is that you?

(note!) The output is three lines and the last line has no content. )
string input and output streamThe string input and output stream operates directly on memory rather than on files and standard output, using the same reading and formatting functions as CIN and cout to manipulate the data in memory, and the declarations of all string stream classes are included in the standard header file <stringstream>. The standard library defines three types of string streams:
Istringstream: String input stream that provides read string functionality.
Ostringstream: String output stream, which provides write string functionality.
StringStream: A string input and output stream that provides read-write string functionality.
using the string input and output stream, you can combine various basic data types into strings, or you can reverse the string to assign values to various variables. The inverse of the string to the variable assignment, merging a variety of basic data type code is as follows:
#include <iostream> #include <sstream>using namespace Std;int main () {int a;float b;string C;char D[20];strin G text= "1 3.14 Hello hello"; string temp;istringstream sin (text);//Inverse string sin>>a;sin>>b;sin>>c;sin> >d;cout<<a<<endl<<b<<endl<<c<<endl<<d;//Merge basic type Ostringstream sout; sout<<a<< "<<b<<" "<<c<<" "<<d<<endl;cout<<sout.str (); return 0;}

C + + STL Fundamentals and Applications (4) output output stream

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.