C++ File & Stream getline()
The getline() function in C++ is used to read a line of text from a file or stream. It is commonly used to process text files and input from the user.
Syntax
getline(stream, str, delim);
stream
: The input stream to read from (e.g.cin
,ifstream
).str
: The string variable to store the line of text.delim
: The delimiter character where the line should end (e.g. newline character\n
).
If the delimiter parameter is not provided, the default delimiter is the newline character \n
.
Example
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file("example.txt");
string line;
if (file.is_open()) {
while (getline(file, line)) {
cout << line << endl;
}
file.close();
}
else {
cout << "Failed to open file" << endl;
}
return 0;
}
Assuming the file "example.txt" exists with the following contents:
Hello
World
Output
Hello
World
Explanation
In the example above, we create an input file stream object file
and associate it with the file "example.txt". We then declare a string variable line
to store each line of text.
We use getline()
inside a loop to read each line from the file until there are no more lines to read. The cout
statement outputs each line to the console.
Use
The getline()
function is commonly used for processing text input from files or from the user. It is useful for extracting lines of text that are separated by delimiters such as a newline character. It is also useful for reading and processing values from CSV (comma-separated values) files.
Important Points
- The
getline()
function reads a line of text from an input stream and stores it in a string variable. - The delimiter parameter is optional and defaults to the newline character
\n
. - The
getline()
function can be used with any input stream type, includingcin
and file input streams. - The function returns the input stream object to enable chained input operations.
Summary
In summary, the getline()
function in C++ is very useful for reading text input from files or from the user. It allows you to easily extract lines of text from input streams, including delimited text such as CSV files. It is a powerful tool for processing text in C++ programs.