Lines are a property of textual data, implying that line-oriented I/O is appropriate for text files but not for binary files. We first used the getline
function, for reading strings from the console, in chapter 8. As cin
is just a stream bound to the console, reading lines from a file is similar to reading strings from the console. Our approach here is to read the lines in a file one at a time into a string variable.
We also learned in chapter 8 that there are two versions of getline
, one for reading C-strings and one for reading instances of the string class. This fact means that we can choose which kind of string variable we wish to use when performing line-oriented I/O. Furthermore, we'll find that the getline
functions have a bit more to offer than just the basic features that we have used in the past.
Each getline
function has two main, overloaded versions. In addition, there is a similar, overloaded version of get
that behaves similar to the C-string versions of getline
.
ifstream input("input.txt"); ofstream output("output.txt); |
|
(a) | |
string Objects | |
---|---|
string line; while (getline(input, line)) output << line << endl; |
string line; while (!input.eof()) { getline(input, line); cout << line << endl; } |
(b) | (c) |
C-Strings | |
char line[100]; while (input.getline(line, 100)) output << line << endl; |
char line[100]; while (!input.eof()) { input.getline(line, 100); cout << line << endl; } |
(d) | (e) |
<<
instead. Two of the patterns embed the read operation in the while-loop control, which provides a compact and efficient mechanism that reads all data in a file. The getline
function reads all the text from the current file position up to and including the next new-line (i.e., line feed) character, and then discards the new-line character.
getline
reads one line of text from the input stream, discards the new-line character, stores the text in the second parameter, and returns input (the first parameter). The overloaded operator() forms an expression converting the returned input into the Boolean value needed to drive the loop.eof
function to drive the while-loop. Each line is read and processed inside the loop.