Skip to content
Related Articles

Related Articles

Improve Article

getline() function and character array

  • Difficulty Level : Easy
  • Last Updated : 28 Nov, 2017

Prerequisite: getline(string) in C++
In C++, stream classes support line-oriented functions, getline() and write() to perform input and output functions respectively. getline() function reads whole line of text that ends with new line or until the maximum limit is reached. getline() is the member function of istream class and has the syntax:

// (buffer, stream_size, delimiter)
istream& getline(char*, int size, char='\n')

// The delimiter character is considered as '\n'
istream& getline(char*, int size)

The function does the following operations:
1. Extracts character up to the delimiter.
2. Stores the characters in the buffer.
3. Maximum number of characters extracted is size – 1.
Note that the terminator(or delimiter) character can be any character (like ‘ ‘, ‘, ‘ or any special character, etc.). The terminator character is read but not saved into a buffer, instead it is replaced by the null character.

// C++ program to show the getline() with 
// character array
#include <iostream>
using namespace std;
int main()
    char str[20];
    cout << "Enter Your Name::";
    // see the use of getline() with array
    // str also replace the above statement
    // by cin >> str and see the difference
    // in output
    cin.getline(str, 20);
    cout << "\nYour Name is:: " << str;
    return 0;

Input :

Aditya Rakhecha 

Output :

 Your Name is:: Aditya Rakhecha

In the above program, the statement cin.getline(str, 20) reads a string until it encounters the new line character or maximum number of characters (here 20). Try the function with different limits and see the output.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :