Input and output stream and file stream operation notes in C + +

Source: Internet
Author: User
Tags setf


1, the flow of control





Iomanip This header file should be included when using formatted I/O.
Stdiostream for mixing C and C + + I/o mechanisms, for example to convert C programs to C + + programs


2. Class inheritance Relationship



iOS is an abstract base class derived from the IStream class and the Ostream class, the Iostream class supports input and output operations, and the Iostream class is a class derived from the IStream class and the Ostream class through multiple inheritance



Class Ifstream inherits Class IStream, Class Ofstream inherits Class Ostream, Class FStream inherits class Iostream
Iostream 4 Stream objects in the header file


Object

Meaning

corresponding equipment

The corresponding class

The corresponding standard file in C language

Cin

Standard input stream

Keyboard

Istream_withassign

Stdin

cout

Standard output stream

Screen

Ostream_withassign

StdOut

Cerr

Standard error stream

Screen

Ostream_withassign

StdErr

Clog

Standard error stream

Screen

Ostream_withassign

StdErr


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



The operator overload function that matches is called according to its type selection. 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 the C language, you must specify the corresponding output format characters separately, which is cumbersome and error-prone.



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



Outputs all data in the stream immediately, regardless of whether the buffer is full, then inserts a newline character and flushes the stream (empties the buffer).



Note If you insert a newline character "\ n" (such as cout<<a<< "\ n"), only the output and line breaks are not flushed, but not the cout stream (but not all compilation systems show this distinction).



3. In iostream, only the input and output of the "<<" and ">>" Operators for standard type data is overloaded, 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 enter and output it with the << and >> operators, follow the heavy operator overload.



The cout stream is typically transmitted to the display output, but can also be redirected to a disk file, while the information in the Cerr stream is only available on the monitor output



Cerr is not through the buffer, directly output information to the monitor, and the information in the clog in the buffer, the buffer is full or when the Endl to the display output


3. Standard input stream cin


The key to mastering the function
Cin.get ()//read in a character and return its value
Cin.get (a parameter)// read in a character and store it in CH
Cin.get (two parameters)//can read a string
Cin.get (three parameters)//can read a string
Cin.getline ()
Cin.ignore ()//read characters and ignore specified characters
Cin.peek ()//Check the next input character without removing the character from the stream
Cin.putback ()//returns a character to a stream



Important
1, using CIN, read from the stream of characters, there is no such character in the stream, read again can only read the remaining
2. Buffer to read all the characters in the stream (that is, empty the buffer) only when the EOF is encountered, the manual hit return, the stream (buffer) is full.



Practice
1, take a character from the stream, and then put it in;
2, judge the first character in the stream is not put in the character;
3, read 10 characters from the stream;
4, ignoring 5 characters from the stream, and then reading 10 characters;
5, 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};
Ranch
// take a character from the stream and put it in
ch1 = cin.get ();
cin.putback (ch1);

// determine if the first character in the stream is the one put in
look = cin.peek ();
if (look == (int) ch1)
{
cout << "cin.peek () puts the character in the first position" << endl;
}
else
{
cout << "cin.peek () does not put the character in the first position" << endl;
}

// Read 10 characters from the stream
cin.get (str1,11);

// Ignore 5 characters from the stream and read 10 more characters
cin.ignore (5);
cin.get (str2,11, EOF);

// Finally read the remaining characters, and finally output all the characters read
cin.getline (str3,100);

// Output the read data
cout << "first character" << ch1 << endl;
cout << "The first set of strings:" << str1 << endl;
cout << "Second set of strings:" << str2 << endl;
cout << "Remaining string:" << str3 << endl;

system ("pause");
return 0;
}
Output:

0123456789abcde9876543210zzzzzzzzzzxxxxxxxxxxxxxyyyyyyyyyyyyy
cin.peek () puts the character in the first position
First character 0
The first set of strings: 0123456789
The second set of strings: 9876543210
The remaining strings: zzzzzzzzzzxxxxxxxxxxxxxyyyyyyyyyyyyy
4, standard output stream cout stream member function
  cout.flush () // Flush the buffer
  cout.put () // Write characters to the stream
  cout.write () // Write a string to the current output stream

  eg: cout.setf (ios :: dec);

         cout.setf (ios :: hex, ios :: basefield); [Recommended]

  Please note: 1. fmtflags setf (fmtflags flags); To use this, you must cancel the current base [cout.unself ()] before you can set a new base.

 2. fmtflags setf (fmtflags flags, fmtflags needed); With this, the second parameter is set to the current base, or when the current base is not known, set to ios_base :: basefield to clear all current possible bases

  Control character, header <iomanip>

 eg: cout << setw (5);

5.File I / O
Since the file device is not the standard default device like the monitor screen and keyboard, and cannot be a predefined global object like cout, we must define an object of this class ourselves.

The ifstream class, which is derived from the istream class, is used to support input from disk files.

The ofstream class, which is derived from the ostream class, is used to support output to disk files.

The fstream class, which is derived from the iostream class, is used to support input and output of disk files.

File Principle
    When a file is opened, there is a file pointer. The initial position of the pointer is specified by the I / O mode. Each read and write starts from the current position of the file pointer. Each time a byte is read in, the pointer is shifted back by one byte. When the file pointer moves to the end, the end-of-file EOF is encountered (the end-of-file character also occupies one byte, and its value is -1). At this time, the member function eof of the stream object is non-zero (usually set to 1) ), The file is over.

    When the file is closed, it actually disassociates the disk file from the file stream, and the original working mode is also invalid. In this way, the file cannot be input or output through the file stream

    File type: 1, ASCII file: Each byte of the file stores data in the form of ASCII code, that is, one byte stores one character, and this file is an ASCII file (or character file).

     2. Binary file: The information in the file is not character data but binary information in bytes, so it is also called a byte file

Common functions Open file:
Method 1: For the file output stream and file stream object, open the file through the constructor of the ofstream class

    Format: ofstream (disk file name, input / output method);

    If ofstream is 0 (false), the open operation failed

    Such as: ofstream fout1 (fname, ios :: out);

    The input and output methods can be used in combination with the "OR" operation ("|"), such as: fstream fout (fname, ios :: out | ios :: in)

Method 2: The file output and input stream objects and file stream objects can be opened by the open function.

    Format: file stream object.open (disk file name, input and output method);

    Return value: 0 (false), the open operation failed

    For example: fout.open (fname, ios :: out)

Close the file:
 After the read and write operations of the opened disk file are completed, the file must be closed, such as: outfile.close ();

File operations
    1. You can use the stream insertion operator "<<" and the stream extraction operator ">>" to input and output data of standard types (>>>> ends when it encounters a space or a newline when it is read).

    2, can also use the file stream put, get, geiline and other member functions for character input and output.

#include <iostream>
using namespace std;
#include "fstream"

int main ()
{
char fname [] = "d: /file1.txt";
char buff [1024] = {0};
/ *********** Write file ************* /
// Method 1 calls the fopen function of the output stream ofstream object
ofstream fout;
fout.open (fname, ios :: out);
if (! fout)
{
cout << "Failed to open file" << fname << endl;
}
fout << "hello world!"; // Write string through left shift operator
fout.flush ();
fout.close ();

// Method 2 calls the constructor of the output stream ofstream object
ofstream fout1 (fname, ios :: out);
if (! fout1)
{
cout << "Failed to open file" << fname << endl;
}
fout1.put (‘h’); // Write characters through put function
fout1.put (‘e’);
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 content
ifstream fin;
fin.open (fname, ios :: in);
fin.getline (buff, 1024); // Read the string through the getline function
cout << buff << endl;
fin.close ();
Ranch
// File stream object reads file content
fstream file1 (fname, ios :: in | ios :: out);
file1 >> buff; // Read string through right shift operator
file1.close ();
cout << buff << endl;


system ("pause");
return 0;
}
Binary file operations
    The read and write of binary files is mainly realized by the member functions read and write of the istream class. The prototype of these two member functions is

     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 (31, "xiaoming");
Teacher t2 (32, "xiaohong");
Teacher t3 (33, "xiaohua");
Teacher t4 (34, "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
 

http://my.oschina.net/u/1783725/blog/700901

Input and output stream and file stream operation notes in C ++

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.