C + + input and output stream and file Flow operation summary _c language

Source: Internet
Author: User
Tags control characters setf

The example of this article for everyone to share in C + + input and output stream and file flow operation notes, for your reference, the specific content as follows

1, the Flow control

Iomanip should include this header file when using formatted I/O.
Stdiostream is used to mix C and C + + I/o mechanisms, such as converting C programs to C + + programs

2. Class inheritance Relationship


iOS is an abstract base class that derives IStream classes and Ostream classes, iostream classes support input and output operations, and iostream classes are classes derived from multiple inheritance from the IStream class and the Ostream class

Class Ifstream inherits Class IStream, Class Ofstream inherits Class Ostream, Class FStream inherits class Iostream

4 Stream objects in iostream header file


cout Supplement
1, with "cout<<" output basic types of data, you can not consider the type of data, the system will determine the type of data

And, depending on its type, invokes the operator overload function that matches it. This process is automatic and the user does not have to intervene.

If you use the Prinf function to output different types of data in C language, you must specify the corresponding output format character, which is cumbersome and error-prone.

2, cout flow in memory corresponding to open up a buffer, used to store the data in the stream , when the cout flow into a Endl,

all data in the stream is immediately output , regardless of whether the buffer is full, and then a newline character is inserted, and the stream is refreshed (emptying the buffer).

Note If you insert a newline character "\ n" (such as cout<<a<< "\ n"), you will only output and wrap, not refresh the cout stream (but not all compilation systems reflect this distinction).

3. Only the input and output of the "<<" and ">>" operators used for standard type data are overloaded in iostream, but the input and output of the type data declared by the user is not overloaded.

If the user declares a new type and wants to input and output it with the "<<" and ">>" operators, do so by the heavy operator overload.

The cout stream is usually transmitted to the display output, but can also be redirected to the disk file, while the information in the Cerr stream can only be output from the monitor

Cerr is to output the information directly to the monitor without passing through the buffer, and the information in the clog is stored in the buffer, the buffer is full or the Endl is output to the monitor.

3. Standard input Flow cin

Focus on the function of mastering
Cin.get ()//reads a character and returns its value
Cin.get (one parameter)//read a character and store it in CH
Cin.get (two parameters)//can read string
Cin.get (three parameters)//can read string
Cin.getline ()
Cin.ignore ()//read characters and ignore specified characters
Cin.peek ()//checks the next entered character and does not remove the character from the stream
Cin.putback ()//return a character to a stream

Important
1, using CIN, read out from the stream of characters, the stream does not have this character, read again can only read the remaining
2, buffer to only in the encounter EOF, manual hit Return, stream (buffer) full, only the characters in the stream read out (that is, empty the buffer)

Practice
1. Take a character from the stream and put it in;
2, judge the flow of the first character is not put in that character;
3, read 10 characters from the stream;
4, ignoring 5 characters from the stream, and then reading 10 characters;
5, the last read the remaining characters, the last output read all the characters

#include <iostream>
using namespace std;

int main ()
{
 char ch1;
 int look;
 Char str1[11] = {0};
 Char str2[11] = {0};
 Char str3[100] = {0};
 
 Take a character from the stream and put it in
 ch1 = Cin.get ();
 Cin.putback (CH1);

 The first character in the stream is judged by the character look
 = Cin.peek ();
 if (look = = (int) ch1)
 {
 cout<< "Cin.peek () the character in the first position" <<endl;
 }
 else
 {
 cout<< "Cin.peek () character not in first position" <<endl;
 }

 Reads 10 characters
 Cin.get (str1,11) from the stream;

 Ignores 5 characters from the stream and reads 10 characters
 Cin.ignore (5);
 Cin.get (str2,11,eof);

 Last read the remaining characters, the last output read all the characters
 cin.getline (str3,100);

 Output read Data
 cout<< "first character" <<ch1<<endl;
 cout<< "first set of Strings:" <<str1<<endl;
 cout<< "Second set of Strings:" <<str2<<endl;
 cout<< "The rest of the string:" <<str3<<endl;

 System ("pause");
 return 0;
}

Output:

0123456789ABCDE9876543210ZZZZZZZZZZXXXXXXXXXXXXXYYYYYYYYYYYY
Cin.peek () put the character in the first position first
character 0 the first
group String: 0123456789
Second set of strings: 9876543210
remaining string: zzzzzzzzzzxxxxxxxxxxxxxyyyyyyyyyyyy

4. Standard output stream cout

Stream member functions

Cout.flush ()//empty buffer
Cout.put ()//write characters into stream
Cout.write ()//writes the string to the current output stream

EG:COUT.SETF (iOS::d EC);

COUT.SETF (Ios::hex,ios::basefield); "Recommended use of this"

Need to note:

1, Fmtflags SETF (fmtflags flags); To use this, you must first cancel the current base "cout.unself ()" Before you can set up a new base

2, Fmtflags SETF (fmtflags flags, fmtflags needed); With this, the second argument is set to the current base, or when the current base is not known, it is set to Ios_base::basefield clears all possible bases of the current

control characters, header files <iomanip>


EG:COUT<<SETW (5);

5. File I/O

Because the file device is not a standard default device like a monitor screen and a keyboard, it cannot be a predefined global object like cout, so we have to define an object of that class ourselves.

The Ifstream class, which is derived from the IStream class, and is used to support input from disk files.

Ofstream class, derived from the Ostream class, to support output to disk files.

The FStream class, derived from the Iostream class, that supports the input and output of disk files.

File principle

File Open has a file pointer, the initial position of the pointer is specified by I/O, each read and write from the current position of the file pointer. Each time a byte is read, the pointer moves back one byte. When the file pointer moves to the end, it encounters the end of file eof (a file terminator also occupies a byte, with a value of-1), at which time the value of the member function EOF of the stream object is not 0 (typically set to 1), indicating that the file is finished.

File shutdown, in effect, is to disassociate the disk file from the file stream, and the original setting does not work, so that the file can no longer be entered or exported through the file stream

File type: 1, ASCII file: Every byte of a file is stored in ASCII code, that is, a byte holds a character, the file is an ASCII file (or character file).

2, binary file: The information in the file is not character data, but the binary form of information in bytes, so it is also known as a byte file

Common functions

Open File:

Mode 1: file output stream, file stream object, open file via constructor of Ofstream class

Format: ofstream (disk filename, input and output mode);

If Ofstream is 0 (false), the open operation fails

such as: Ofstream fout1 (fname,ios::out);

The input and output methods can be used in combination with the "or" Operation ("|" The way, such as: FStream Fout (Fname,ios::out|ios::in)

Mode 2: file output and input stream objects, file stream objects, can open the file through the Open function

Format: File stream object. Open (disk filename, input and output mode);

Return value: 0 (FALSE), open operation failed

such as: Fout.open (fname,ios::out)

To close a file:

After the read-write operation of an open disk file is complete, you must close the file such as: Outfile.close ();

File actions

1, you can use the flow insert operator "<<" and the Flow extraction operator ">>" input the output of the standard type of data (>> read out when the space, wrapped end).

2, can also use the file flow of put, get, geiline and other member functions for the input and output of characters.

#include <iostream> using namespace std;
 #include "fstream" int main () {char fname[] = "D:/file1.txt";
 Char buff[1024]= {0};
 /*********** Write file *************///mode 1 output stream Ofstream object call fopen function Ofstream fout;
 Fout.open (fname,ios::out);
 if (!fout) {cout<< "Open file Failed" <<fname<<endl; } fout<< "Hello World!";
 Writes the string Fout.flush () by the left shift operator;

 Fout.close ();
 Mode 2 invokes the constructor function of the output stream Ofstream object Ofstream fout1 (fname,ios::out);
 if (!FOUT1) {cout<< "Open file Failed" <<fname<<endl; } fout1.put (' H ');
 Writes the character fout1.put (' E ') through the PUT function;
 Fout1.put (' l ');
 Fout1.put (' l ');
 Fout1.put (' O ');
 Fout1.put (' \ n ');
 Fout1.flush ();

 Fout1.close ();
 File stream object Write file FStream file2 (fname,ios::in|ios::out);
 file2<< "abdfd\n";
 file2<< "11111\n";
 File2.flush ();

 File2.close ();
 /*********** Read file *************///input stream Ifstream object reads file contents ifstream fin;
 Fin.open (fname,ios::in); Fin.getline (buff,1024); 
 Reading a string through the Getline function cout<<buff<<endl;
 
 Fin.close ();
File stream object Read file contents FStream file1 (fname,ios::in|ios::out); file1>>buff;
 Read the string File1.close () by the right shift operator;


 cout<<buff<<endl;
 System ("pause");
return 0;

 }

Binary file operations

The reading and writing of binary files are mainly implemented by the member functions of the IStream class, read and write. The prototypes for these two member functions are

istream& Read (char *buffer,int len);

ostream& Write (const char * buffer,int len);

#include <iostream> using namespace std; #include <fstream> class Teacher {Public:teacher () {} Teacher (int Age,char name[20]) {This->age = age
 ;
 strcpy (This->name,name); } void Prinfinfo () {cout<< "Teacher name:" <<this->name<< "Age:" <<this->age<<endl
 ;
 } Private:int age;
Char name[20];

};
 int main () {Teacher T1 ("Xiaoming");
 Teacher T2 ("Xiaohong");
 Teacher T3 ("Xiaohua");
 Teacher t4 ("xiaoxin");
 Char fname[] = "D:/file2";
 FStream FS (fname,ios::binary|ios::out);
 if (!FS) {cout<< "File open Failed" <<endl;
 } fs.write ((char *) &t1,sizeof (Teacher));
 Fs.write ((char *) &t2,sizeof (Teacher));
 Fs.write ((char *) &t3,sizeof (Teacher));
 Fs.write ((char *) &t4,sizeof (Teacher));
 Fs.flush ();

 Fs.close ();
 FStream FS2 (fname,ios::binary|ios::in);
 if (!FS) {cout<< "File open Failed" <<endl;
 } Teacher TT;
 Fs2.read ((char *) &tt,sizeof (Teacher));
 Tt.prinfinfo (); Fs2.read ((char *) &tT,sizeof (Teacher));
 Tt.prinfinfo ();
 Fs2.read ((char *) &tt,sizeof (Teacher));
 Tt.prinfinfo ();
 Fs2.read ((char *) &tt,sizeof (Teacher));
 Tt.prinfinfo ();

 Fs2.close ();
 System ("pause");
return 0;

 }

Output:

Teacher name:xiaoming  age:31
Teacher name:xiaohong
age:32 Teacher Name:xiaohua age:33 Teacher name:xiaoxin  age:34

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.