The <iostream> Library

Input/output (I/O) in C++ relies on overloading the operators << (for writing) and >> (for reading). All output classes derive from ostream, so overloading the >> operator for ostream means that you can use that operator for any output class. It is important to realize that file output is buffered; that is, the data is not immediately written to the actual disk file. This is done to speed up I/O because disk access occurs much more slowly than memory access. You can flush file streams (that is, write them to disk) by using the ostream::flush() method when the streams are closed. This is why it is important that file streams are closed properly.

The standard streams are cin, cout, and cerr. (cerr is used for error output. It will also appear on the screen, but is unbuffered, so no output is lost.) <iostream> also defines some special objects, called manipulators, that modify the stream; an example is endl, which inserts a newline and flushes the stream.

Reading Data

Data items are read by using operator>>, which usually ignores whitespace (including newlines). You call eof() to determine whether a stream is finished, and you call bad() to determine whether an error has occurred. If in is an input stream, then ! in is true if the stream is bad or past the end of the file; you can test in >> var directly, as follows, because istream has a conversion operator to integer:

while (in >> x >> y) diff += (x – y);

Reading Character Strings

The extraction operator (>>) is overloaded for both standard strings and plain arrays of characters. In both cases, the next token (that is, text delimited by whitespace) is read in; reading into a string is safer than reading into an array because strings do not overflow (they are resizeable); however, raw character data is faster than string data. (Safety versus speed is a common choice in programming, and C++ offers both.) If you want to read a whole line of text, you can use the two main versions of getline(). The second form of getline() is implemented as a function, not as a method, and it takes a standard string argument.

istream& istream::getline(char *buff, int sz);
istream& getline(istream& is,string& s);

Both versions of getline() return a reference to the input stream, which can be used in two ways. First, you can chain calls, as shown in the following example. Second, you can test the return value, relying on the conversion operator:

;> const int BSIZE = 256;
;> char b1[BSIZE],b2[BSIZE];
;> string s;
;> cin.getline(b1,BSIZE).getline(b2,BSIZE);   // two lines are fetched
							one
							two
;> ifstream in("temp.txt");
;> while (getline(in,s)) cout << s << endl;   // while in.eof() isn't true
						

<iomanip> defines the setw() manipulator, which can be used as follows to force the input width, if you need to read the next n characters:

// stream contains 'dolly the sheep'
in >> setw(4) >> s; // s contains 'doll'

Reading File Streams

You can read files by using the ifstream class, which is derived from istream, and you can write files by using the ofstream class, which is derived from ostream. You use open() to access a file; it returns false if the operation failed. You should always check whether the operation failed. The file needs to be closed at the end, and the class destructor does this. Note that open() does not currently take a string argument, so you have to use s.c_str() to get the underlying character data if you are using standard strings.

The file stream open() method can take an extra argument, which controls how the file is opened. This table shows the main ios flags and their meanings; they may be combined using |:

ios::in         -file opened in input mode
ios::out        -file opened in output mode
ios::app        -file append; any writing starts at end of existing file
ios::binary     -file opened in binary mode; no text translation
ios::in | ios::out       -both read and write!
ios::app | ios::binary   -append to binary file

Formatting Output

You control floating-point precision with the setprecision() manipulator; you control the width of the output field with setw(), as in the following code; please see stdlib est-io.cpp:


void test_out()
{
  int val = 648,k;
  double pi = 4*atan(1.0); // a way to calculate PI...

  // note that it is necessary to  switch back to decimal....
  cout << "Hex " << hex << val << " Dec " << dec << val << endl;
  // floating-point precision can be set using setprecision
  cout << "Default precision   " << pi << endl;
  cout << "Precision(12) " << setprecision(12) << pi << endl;
  cout << "Precision(6)  " << setprecision(6) << pi << endl;
  cout << "Precision is (" << cout.precision() << ") " << endl;

  // can control the width using the setw() manipulator
  // note that the width only applies to the _next_ field!
 for(int i = 0; i < 5; i++)
     cout << setw(10) << i*pi;
 cout << endl;

// setting formatting flags: this forces positive numbers to be
// displayed with an explicit plus sign.
 cout.setf(ios::showpos ) ;
 for(int i = 0; i < 5; i++)
    cout << 10*i << ' ';
 cout << endl;

}


Hex 288 Decimal 648
Default precision   3.14159
Precision(12) 3.14159265359
Precision(6)  3.14159
Precision is (6) 3.14159
         0   3.14159   6.28319   9.42478   12.5664
+0 +10 +20 +30 +40

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.159.178