C + + input/output is provided by the standard library, which supports reading and writing of files, control Windows, and string objects.
8.1 Object-oriented libraries
The IO type is defined in three separate header files, iostream defines the type of read-write control window, fstream defines the type of read-write named file, Sstream defines the type used to read and write the string object stored in memory.
If a function has a reference parameter to a base class type, you can pass an object of its derived type to the function. This is the function that operates on istream&, or it can be invoked using Ifstream or Istringstream objects.
The standard library defines a set of related types, supports the wchar_t type, and each class is prefixed with a "w", which is distinguished from the version of the Char type. such as Wiostream, Wfstream, Wstringstream and so on.
IO objects cannot be copied or assigned
1) The stream object cannot be copied, so it cannot be stored in a vector or other container;
2) The formal parameter or return type cannot be a stream type. To pass or return an IO object, you must specify a pointer or reference to the object.
8.2 Item StatusCondition status
Badbit marks a system-level failure, cannot be recovered, Failbit is an IO error, usually can be fixed, eofbit is set when a file terminator is encountered, and the Failbit is set at the same time.
If either bad, fail, or EOF is true, the stream is in an error state, and if none of the three are true, the good operation returns True.
The clear operation resets the condition to a valid state.
The SetState operation opens a specified condition that indicates that a problem occurred.
Query and control of flow status
int ival;//read CIN and test only for EOF; Loop is executed even if there be other IO failureswhile (Cin >> ival,!cin.eof ()) { if (Cin.bad ())//Input St Ream is corrupted; Bail out throw Runtime_error ("IO stream corrupted"); if (Cin.fail ()) {//Bad input cerr<< ' bad data, try again ';//warn the user cin.clear (istream::failbit); /Reset the stream continue;//Get Next input }//OK to process ival}
Access to Conditional state
The Rdstate member function returns a value of type iostate that represents the current entire condition state of the stream.
Remember current state of cinistream::iostate old_state = Cin.rdstate (); Cin.clear ();p rocess_input (); Use Cincin.clear (old_state); Now the reset CIN to the old state
Multi-state processing
Use a bitwise OR to generate a value that "passes two or more state bits" in a single call
Sets both the Badbit and the Failbitis.setstate (Ifstream::badbit | ifstream::failbit);
Generates a value that corresponds to both the badbit and failbit bits are open, both bits are set to 1, and the other bits of the value are 0
8.3 Management of output buffers
Each IO object manages a buffer that stores the data that the program reads and writes. The following conditions can cause the contents of the buffer to be refreshed
1) program ends normally
2) At some indeterminate time, the buffer is full and is refreshed before new data is written
3) flush buffer with manipulation modifier explicitly
cout << "hi!" << flush; Flushes the buffer; Adds no datacout << "hi!" << ends; Inserts a null, then flushes the buffercout << "hi!" << Endl; Inserts a newline, then flushes the buffer
4) After each operation, set the internal state of the stream with the UNITBUF operator, thereby emptying the buffer
cout << unitbuf << "First" << "second" << Nounitbuf;is equivalent to Writingcout << "first" << flush << "second" << flush;
Unitbuf flushes the stream after each write operation, and the NONUNITBUF operator restores the stream to a normal, system-managed buffer refresh mode.
5) associates an output stream with an input stream, flushing its associated output buffers when the input stream is read
The standard library binds cout to CIN by default
The tie function can be called with IStream or ostream, using a pointer parameter that points to the Ostream object. If you pass argument 0 when you call the tie function, the bundle that already exists on that stream is broken.
Cin.tie (&cout); Illustration only:the Library ties cin and cout for usostream *old_tie = Cin.tie (); cin.tie (0); Break tie to cout, cout no longer flushed when CIN is Readcin.tie (&CERR); Ties CIN and Cerr, not necessarily a good idea!//... cin.tie (0); Break tie between Cin and Cerrcin.tie (Old_tie); Restablish normal tie between CIN and cout
8.4 Input and output of the file
FStream, in addition to inherited behavior, defines two of its own new operations, Open,close
Two types of initialization of stream objects
Construct an ifstream and bind it to the file named Ifileifstream infile (Ifile.c_str ()); Ifstream infile; Unbound input file Streaminfile.open ("in"); Open file named "in" under the current directory
For historical reasons, the IO standard library uses a C-style string instead of a C + + string as the file name.
Check if File Open is successful
Check that the Open Succeededif (!infile) { cerr << ' error:unable to open input file: ' << ifile & lt;< Endl; return-1;}
To re-bundle a file stream with a new file (the current file stream must be closed before the file stream changes the associated file)
Ifstream infile ("in"); Opens file named "in" for Readinginfile.close (); Closes "in" Infile.open ("Next"); Opens file named "Next" for reading
Clears the state of a file stream
Reusing an existing stream object, the while loop must remember to close and empty the file stream at each iteration, because the stream object is in an error state when the file is opened successfully and read until the end of the file or other error, and any attempt to read the stream object will fail.
Ifstream Input;vector<string>::const_iterator it = Files.begin ();//For each file in the Vectorwhile (it! = Files.en D ()) { Input.open (it->c_str ());//Open the file //If the file is OK, read and "process" the input if (!in put) break ;//Error:bail out! while (input >> s)//doing the work on this file process (s); Input.close (); Close file when we do with it input.clear (),//reset state to OK ++it,//increment iterator to get next File
File mode
In read open, ifstream default mode
Out write open, ofstream default mode, file will be emptied
App End Write Open
Ate open navigate to end
Trunc Empty Open
Binary binary form Open
A program that opens and checks the input file
Opens in binding it to the given fileifstream& Open_file (ifstream &in, const string &file) { in.close (); Close in case it is already open in.clear ();//clear any existing errors //If the open fails, the stream WI ll be in a invalid state In.open (File.c_str ());//Open the file we were given return in;//condition State is G Ood if Open succeeded}
8.5 String StreamUse of StringStream objects
string line, Word; Would hold a line and word from input, respectivelywhile (getline (CIN, line)) {//read a line from the input into line< c6/>//do per-line processing Istringstream Stream (line),//bind to stream to the line, we read while (Stream > > Word) {//read a WORD from line //Do Per-word processing }}
Conversions provided by StringStream
int val1 = Val2 = 1024;ostringstream format_message;//ok:converts values to a string Representationformat_message & lt;< "Val1:" << val1 << "\ n" << "val2:" << val2 << "\ n";
STR member obtains the string associated with a Stringstreamistringstream input_istring (Format_message.str ()); string d Ump Place-to-dump the labels from the formatted message//extracts the stored ASCII values, converting back to arithmetic t ypesinput_istring >> dump >> val1 >> dump >> val2;cout << val1 << "" << val2 &L t;< Endl; Prints 512 1024
When you read a string using the input operator, the whitespace character is ignored.
[C++primer] [08] Standard IO Library