Skip to content
Related Articles

Related Articles

std::basic_istream::getline in C++ with Examples
  • Last Updated : 22 May, 2020

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 delimeter '|'
    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;
}

chevron_right


Output:

123
aef
5h

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 delimeter ', '
    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;
}

chevron_right


Output:

GeeksforGeeks
A
Computer
Science
Portal
For
Geeks

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

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :