getline( ) Function:
The getline( ) function is similar to gets() function. Both allow inputting a string. But gets( ) function works with standard
input stream. Whereas getline( ) can
work with cin object as well as with
any other user-defined input stream object.
Another notable
difference between these two function is, gets(
) function by default uses new-line (‘\n’) as a string terminator and leaves
the character in the input stream. Whereas getline(
) function removes the terminating character (new-line by default) from the input stream.
Moreover with
the getline( ) function you have
option to specify your own string terminating character, also the maximum
number of characters form the line to pick. String terminates when specified
maximum number of characters picked for the input stream or specified string
terminating character is encountered in the input stream, whichever occurs
earlier.
Syntax:
Device.getline(char_variable,integer_limit,“terminating_character");
Example
1:
Char
name[30];
cin.getline(name,
20, ‘.’);
Here, the input will be
terminated by the presence of (.) in the input stream or by maximum limit 19 no.of characters, which ever occurs earlier. See the programs given below illustrating the use of
getline( ).
Example
2
//Program
demonstrating use of getline function with cin object
#include<iostream.h>
int
main()
{
char
buf[30];
cout<<"\n
Enter a line and terminarte by .(dot): ";
cin.getline(buf,30,'.');
cout<<buf;
return
0;
}
Output:
RUN 1
In the first run dot (.) is
considered as string terminator.
RUN 2
In second RUN 29 characters are
accepted. Because a maximum limit was set to 30.
Example
3
/*Program
demonstrating the use of getline with user define input stream which represents
a disk file "myfile.txt"*/
#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>
#include<conio.h>
int
main()
{
clrscr();
char
myline[70];
int
LC=0;
ifstream
infile("myfile.txt");
if(!infile)
{
cerr<<"Filed to open the input
file";
exit(1);
}
while(1)
{
infile.getline(myline,70,'.');
if(infile.eof()) break;
LC++;
cout<<LC<<":
"<<myline<<'\n';
}
infile.close();
getch();
return
0;
}
Output:
Thank you. Its helpful
ReplyDelete¡Excelent! tnak you
ReplyDelete