What is getline() method in C\C++?
Overview
The getline() function is used in C++ to read a string from the input. It helps to retrieve characters from the input.
Syntax
istream& getline(isstream& fin, string& str, char delim);
Parameters
Let’s discuss the parameters of the function:
fin: An object ofistreamclass used to send a command to function about reading the input from the stream.str: A string object to store input.delim: A delimitation character used to stop function after reaching the target character.
Example
Let’s look at the code below:
main.cpp
data.txt
#include <iostream>#include <fstream>#include <string>int main() {std::string fname, lname, nationality;// ifstream instancestd::ifstream fin;// opening a file named data.txtfin.open("data.txt");if (fin.is_open()) {// extract first namestd::getline(fin, fname);// extract last name from filestd::getline(fin, lname);// extract nationality or countrystd::getline(fin, nationality);// closing opend filefin.close();// print data on consolestd:: cout << "\n-----Entered details-----\n" << '\n';std::cout << "Name: " << fname << std::endl;std::cout << "Father Name: " << lname << std::endl;std::cout << "Nationality: " << nationality << std::endl;} else {std::cout << "Unable to open file.";}}
Explanation
Here is a line-by-line explanation of the above code:
main.cpp
- Line 8: We create
ifstreaman instance to read from a file. - Lines 10 to 11: We load a file named
data.txtand validate it. And usefin.is_open()function to check whether the specified file is loaded or not. - Lines 13, 15 and 17: We invoke
std::getline()method to extract first name (fname), last name (lname), and nationality from the loaded file. - Line 19: We close the opened file using
fin.close(). - Lines 22 to 24: We print data to the console.
data.txt
- Line 1: It contains the first name.
- Line 2: It contains the last name or father name.
- Line 3: It contains the nationality of person.