1
In order to be able to read from a file an tt(ifstream) object must be
2
created, in order to be able to read from a string stream an tt(istrstream)
3
object must be created.
5
To open a file to read from, the tt(ifstream) constructor receives
6
the name of the file to be opened:
8
center(tt(ifstream in("infile");))
10
By default this will result in the opening of the file for reading. The file
11
must exist for the tt(ifstream) object construction to succeed.
12
Instead of the shorthand form to open a file for reading, and explicit tt(ios)
13
flag may be used as well:
15
center(tt(ifstream in("infile", ios::in);))
17
As with the tt(ofstream) objects, tt(ifstream) objects may be constructed
18
first, and opened later:
25
Normally, information will be extracted from the tt(ifstream) object using
26
the extraction operator rshift(), in the way it is used with the standard stream
29
center(tt(in >> x >> y;))
31
By default, the extraction operator skips blanks: between words, between
32
characters, between numbers, etc.. Consequently, if the input consists of the
33
following information: verb(
39
then the next code fragment will read tt(12) and tt(13) into tt(x) and tt(y),
40
will then return the characters tt(a) and tt(b), and will finally read
41
tt(hello) and tt(world) into the character array tt(buffer):
50
in >> x >> y >> c >> c >> buffer >> buffer;
52
Notice that no format specifiers are necessary. The type of the variables
53
receiving the extracted information determines the nature of the extraction:
54
integer values for tt(int)s, white space delimited strings for tt(char [])s,
57
Just like the tt(fopen()) function of bf(C) may fail, the construction of the
58
tt(ifstream) object might not succeed. When an attempt is made to
59
create an tt(ifstream) object, it is a good idea to test the successful
60
construction. The tt(ifstream) object returns 0 if its construction failed.
61
This value can be used in tests, and the code can throw an exception (see
62
section ref(EXCEPTIONS)) or it can handle the failure itself, as in the
72
in(""); // creating 'in' fails
76
cerr << "creating ifstream object failed\n";
82
Analogous to an tt(ifstream) object, an tt(istrstream) object can be
83
created. Here no filename is required. E.g.,
84
centt(istrstream text("hello world");)
85
opens an tt(istrstream) object that is initialized by an ascii-z string.