Getline Function in C++
The “getline” Function:
The “getline” is used to read a text file one line at a time. This function reads a sequence of characters, including spaces, until the end-of-line (or ‘\0’) character is reached. Its syntax is:
object.getline(string, n);
where:
object: represents the created object of ifstream (or fstream) class.
getline: represents a member function of the object.
string: represents a string type variable used to store data of one line that is read from the file.
n: represents total number of characters that arc to he read for one line from the text file. It is an integer value.
Program:
Write a program to read a text tile, one line at a time, and display the contents on the screen.
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
#include <stdlib.h>
main ( )
char str [100];
ifstream rrr (“data.txt”);
clrscr ( );
if (! rrr)
{
cerr << “File opening error” <<endl;
exit(l);
}
while (rrr)
{
rrr.getline ( str, 80 );
cout << str << endl;
}
}