The getline()
function is used in C++ to read a string from the input. It helps to retrieve characters from the input.
istream& getline(isstream& fin, string& str, char delim);
Let’s discuss the parameters of the function:
fin
: An object of istream
class 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.Let’s look at the code below:
#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.";}}
Here is a line-by-line explanation of the above code:
main.cpp
ifstream
an instance to read from a file.data.txt
and validate it. And use fin.is_open()
function to check whether the specified file is loaded or not.std::getline()
method to extract first name (fname), last name (lname), and nationality from the loaded file.fin.close()
.data.txt