Skip to content
Related Articles

Related Articles

getline() Function and Character Array in C++

Improve Article
Save Article
Like Article
  • Difficulty Level : Easy
  • Last Updated : 17 Jan, 2022

The C++ getline() is a standard library function that is used to read a string or a line from an input stream. It is a part of the <string> header. The getline() function extracts characters from the input stream and appends it to the string object until the delimiting character is encountered. Must read the article getline(string) in C++ for more details.

In C++, stream classes support line-oriented functions, getline() and write() to perform input and output functions respectively. 

Getline Character Array: This function reads the whole line of text that ends with a new line or until the maximum limit is reached. getline() is the member function of istream class.

Syntax:

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

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

Parameters:

  • char*: Character pointer that points to the array.
  • Size: Acts as a delimiter that defines the size of the array.

The Function Does the Following Operations: 

  • Extracts character up to the delimiter. 
  • Stores the characters in the buffer. 
  • The 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. 

For Example:

Input: Aditya Rakhecha 

CPP




// C++ program to show the getline() with
// character array
#include <iostream>
using namespace std;
  
// Driver Code
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;
}


Output

 Your Name is:: Aditya Rakhecha

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

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!