Open In App

std::basic_istream::getline in C++ with Examples

Last Updated : 06 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The std::basic_istream::getline is used to extract the characters from stream until end of line or the extracted character is the delimiting character. The delimiting character is the new line character i.e ‘\n’. This function will also stop extracting characters if the end-of-file is reached if input is taken using file.
Header File: 

#include <iostream>

Syntax: 

basic_istream& getline (char_type* a, 
                            streamsize n )

basic_istream& getline (char_type* a, 
                            streamsize n, 
                             char_type delim);

Parameters: It accepts the following parameters: 
 

  • N: It represent maximum number of character pointed by a.
  • a: It is the pointer to string to store the characters.
  • stream: It is an explicit delimiting character.

Return Value: It returns the basic_istream object.
Below are the program to demonstrate basic_istream::getline():
Program 1: 

CPP




// C++ program to demonstrate
// basic_istream::getline
 
#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
    // Given string
    istringstream gfg("123|aef|5h");
 
    // Array to store the above string
    // after streaming
    vector<array<char, 4> > v;
 
    // Use function getline() to stream
    // the given string with delimiter '|'
    for (array<char, 4> a;
         gfg.getline(&a[0], 4, '|');) {
        v.push_back(a);
    }
 
    // Print the strings after streaming
    for (auto& it : v) {
        cout << &it[0] << endl;
    }
 
    return 0;
}


Output: 

123
aef
5h

 

Program 2: 

CPP




// C++ program to demonstrate
// basic_istream::getline
 
#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
    // Given string
    istringstream gfg("GeeksforGeeks, "
                      " A, Computer, Science, "
                      "Portal, For, Geeks");
 
    // Array to store the above string
    // after streaming
    vector<array<char, 40> > v;
 
    // Use function getline() to stream
    // the given string with delimiter ', '
    for (array<char, 40> a;
         gfg.getline(&a[0], 40, ', ');) {
        v.push_back(a);
    }
 
    // Print the strings after streaming
    for (auto& it : v) {
        cout << &it[0] << endl;
    }
 
    return 0;
}


Output: 

GeeksforGeeks
A
Computer
Science
Portal
For
Geeks

 

Reference: http://www.cplusplus.com/reference/istream/basic_istream/getline/



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads