×

getline() Function and Character Array in C++

In this article, we will explore about some concepts on getline() function and character array in the most useful language C++.

The getline() method in C++ is simply a standard library function that extracts a string or a line from an input stream. It is included in the <string> header. The getline() function appends characters from the input stream to the string object until the delimiting character is encountered. For further information, see the C++ article getline(string).

What Exactly is getline()?

Bjarne Stroustrup designed C++, a popular general-purpose programming language. It is based on the C programming language and was originally known as "C with Classes." The programming language adheres to object-oriented programming principles and is the world's fourth most popular programming language. This post will educate students about C++ getline, which is a fundamental idea in programming. The C++ getline() method is a built-in function that can be supplied in a <string. h> A header file that receives and reads single and multiple line string input from the input stream. The cin object in C++ also takes user input, but only single-word or single-line input.  This is when the getline() function comes in help.

Stream classes in C++ support line-oriented functions such as getline() and write(), which conduct input and output operations, accordingly.

The function keeps accepting input and appending it to the string until it encounters a key defining character. As a result, we can utilise it to continue adding inputs for longer strings. The following are some of the most prevalent applications:

  • Using the entire name
  • Taking information such as address and bio
  • Requesting any long-form or multi-line input

Getline Character Array:

This function reads the entire line of text that ends with a new line or until the maximum limit is reached. getline() is a member method of the istream class."

Parameters:

  • char*: A character pointer pointing to an array.
  • Size: Serves as a delimiter for the array's size.

The Function focuses on the Tasks:

  • Character is extracted up to the delimiter.
  • The characters are saved in the buffer.
  • Size - 1 is the maximum amount of characters retrieved.

It should be emphasised that the terminator (or delimiter) character could be any character (for example, ', ', or any special character). The terminator character is read but not saved in a buffer; instead, it is replaced by the null character.

For instance:

Input: Ms. Saha

Syntax:

// (buffer, stream_size, delimiter)
istream& getline(char*, int size, char='\n')
// The delimiter character is perceived as '\n'
istream& getline(char*, int size)

C++ Program:

// Demonstrating getline() with a character array in CPP
#include <iostream>
using namespace std;


// Driver's Code
int main()
{
	char str1 [ 20 ];
	cout << "Enter Your Name::";


	// see how to use getline() with array str1 Modify the above statement with cin >> str to notice the difference in output.
	cin.getline ( str1, 20 );


	cout << "\nYour Name is:: " << str1;
	return 0;
}

Output:

Enter Your Name::Ms. Saha


Your Name is:: Ms. Saha

Clarification: The expression cin.getline ( str1, 20 ); in the above code reads a string until it meets the new line character or the maximum number of characters (here 20). Examine the output of the function with various restrictions.

Examples of C++ Getlines to help one Understand How They Work

To learn about the C++ getline() method, accept the user's name as input and show a greeting along with it. For clarity, you will begin by using the cin object rather than the getline() function. You will eventually utilise the function to distinguish between the two.

Instance 1: By using cin Object

C++ Language:

#include <iostream>
#include<string.h>


using namespace std;


int main ()
{
 // declaring variable  
    string UserName; 


    // Asks user for an input
    std::cout << "What is your name? :" << std::endl;


    cin >> UserName;  


    // greetings printing


    cout << "\nWelcome to Tutorial and Examples " << UserName;


    return 0;


}

Output:

What is your name? :
Tiya Saha


Welcome to Tutorial and Examples Tiya

As we can see in the output, only the user's first name was displayed. This happens because the compiler ceased scanning the input stream when it came across a space (" ") character. As a result, the cin object never read multi-word or multi-line input. That is why you must employ the getline function.

Instance 2: By using C++ Getline with Two Parameters

Let's use the C++ getline() method to address the user from the previous example by her full name. You will use the getline() function with two parameters in this example. This indicates you won't be able to pass the delimiting character. We'll see how it works.

C++ Program:

#include <iostream>


#include<string.h>


using namespace std;


int main ()
{
// declaring variable
    string UserName;


    // Asks user for an input


    std::cout << "What is your name? :" << std::endl; 


    // using the func getline


    getline ( cin, UserName );


    cout<<"\nWelcome to Tutorial and Examples "<< UserName;


    return 0;


}

Output:

What is your name? :
Tiya Saha


Welcome to Tutorial and Examples Tiya Saha

This time, the output includes both David and Morrison. It means that even after seeing a space character, the C++ getline() method can continue reading the input stream.

Instance 3: By using C++ Getline with Three Parameters

A delimiting character can also be used to prevent the getline() method from reading the input stream once it meets that character. To demonstrate this, use a space (" ") as a delimiting character to block the function from accessing the last name after the space. As a result, it will produce the same results as when you utilised the cin object.

C++ Program:

#include <iostream>
#include<string.h>


using namespace std;


int main ()
{
// declaring variable  
    string UserName;  


// Asks user for an input
    std::cout << "What is your name? :" << std::endl;


        // using the func getline


    getline ( cin, UserName, ' ' );


    cout << "\nWelcome to Tutorial and Examples " << UserName;


    return 0; 
}

Output:

What is your name? :
Tiya Saha


Welcome to Tutorial and Examples Tiya

As we can notice, even though we used the getline() function, the result only displayed the first name because space is a delimiting character.

How to Make a Character Array Using C++ Getline

For a character array, you can alternatively utilise the C++ getline() function. The syntax, though, differs from what you've seen for the strings. The following is the syntax for using the getline character array:

istream& getline(char* , int size);

In the preceding syntax:

  • char: The character pointer pointing to the array.
  • int size: This specifies the maximum array size. As a result, it serves as a delimiter, as surpassing the limit terminates the reading.

Instance 4: Getline Character Array Use

C++ Program:

#include <iostream>
#include<string.h>


using namespace std;
// Driver’s Code
int main ()
{  
// array declaration
    char colors [ 50 ]; 


    cout << "Enter the name of some colors: ";   


    // using function getline
    cin.getline ( colors, 50 );
    std::cout << "\nColors list :"<< colors << std::endl;
    return 0;


} 

Output:

Enter the name of some colors: Blue, Pink, Red


Colors list :Blue, Pink, Red

Instance 5: C++ Getline for Character Array and Char Limit Exceeding

In this example, we will deliberately surpass the char limit to watch how the C++ getline() method responds and stops reading the input stream.

C++ Program:

#include <iostream>
#include<string.h>


using namespace std;
// Driver’s Code
int main ()
{  


// array declaration
    char colors [ 50 ];


    cout<< "Enter the name of some colors: ";  


    // using function getline


    cin.getline ( colors, 50 );


    std::cout << "\nColors list :"<< colors << std::endl;


    return 0;


}

Output:

Enter the name of some colors: Blue, Pink, Red, White, Black, Violet, Green, Yellow, Orange


Colors list :Blue, Pink, Red, White, Black, Violet, Green, Yel

As shown in the result, the getline() function stopped reading the input stream after the character limit of 30 was reached.

Conclusion:

This article introduced us about the C++ getline() function. We can also see it used for character arrays, with examples. One may now utilise it to easily obtain long-form multi-line inputs from users. Understanding and employing the C++ getline is a basic feature in this programming language. The tutorial will show key concepts such as C++ arrays and C++ for loops. Once one has mastered the fundamentals, they can move on to more complex concepts in C++ coding.


Related Topics

C++ Program to find the largest number formed from an array

Given an array, write a program to find the largest number that will be formed from the elements of the array. Arrangement should be done in such a way that...

4 minutes read.

C++ Exception Handling

Exception is an unexpected problem that occurs at program run time. This problem might include condition such as division by zero, running out of memory space, array out of bonds, etc....

2 minutes read.

How to create a stack in C++

A stack is a data structure, which is of linear type. A specific order has to be followed while inserting and deleting the elements from the stack. Generally, stack follows...

5 minutes read.

Free vs delete() in C++

Free vs delete() in C++ In this section, we will learn about the free() function and also create a C ++ program of the delete operator. What is free() Function in C++? In...

4 minutes read.

Implementation of a Falling Matrix in C++

In many Hollywood and Bollywood movies, we might have seen a programmer who will be referred to as a hacker all the time for some random reason which the writer...

3 minutes read.

4-Dimensional Array in C/C++

A four-dimensional (4D) array is an array of three-dimensional (3D) arrays, or in other words we can say that a 4- dimensional array is an array of arrays of arrays...

3 minutes read.

External merge sort in C++

External merge sort in C++ External sorting is a concept for a group of sorting algorithms capable of handling large data volumes. External sorting is needed if the information getting sorted...

9 minutes read.

Initialize Array of objects with parameterized constructors in C++

Initialize Array of objects with parameterized constructors in C++ When a class is defined, only the specification for the object is specified; no memory or capacity is allocated. You need to...

3 minutes read.

Structure of C++ Program

Many people believe that C++, an object-oriented programming (OOP) language, is the finest language for developing demanding applications. A superset of the C language is C++. Java, a closely comparable...

4 minutes read.

C++ Expressions

C ++ equations are made up of operators, constants and variables arranged according to language rules. It may also include function calls that give results. To calculate the value, the...

4 minutes read.

Pointers in C++

Pointers are a powerful feature in the C++ programming language, allowing developers to directly manipulate memory addresses and create more efficient and dynamic programs. However, pointers can also source various...

3 minutes read.

List back () function in C++ STL

The list::back () function of the C++ STL returns a direct reference to the last element in the list container. This function varies from list::end (), which just returns an...

2 minutes read.

Abstract class in C++

In this article, you will get exposure to an abstract class in C++. We will discuss this topic using some practical examples too. To understand the abstract classes, you should...

6 minutes read.

sort() function in C++

This tutorial covers the various built-in sort functions found in the C++ algorithm’s library.  What Does C++ Sort Mean? The concept of sorting in C++ entails rearranging an array's elements in a...

3 minutes read.

Substring in C++

A substring is a function in c++ that is imported from the string library. An element of a string is called a substring. A substring contains two parameters length and...

2 minutes read.

Boost split in C++ library

Boost::split in C++ library Boost offers strong tools for adding mature, well-tested libraries to the C++ standard library. The boost: split function, which is a component of the Boost string algorithm...

2 minutes read.

C++ Void Pointer

A void pointer is a general purpose pointer that can have an address of any data type but is not related to any data type. Void Pointer Syntax: void *ptr;  We can't...

2 minutes read.

C++ Polymorphism

Polymorphism refers to the fact that something exists in several forms. Polymorphism, in simple terms, is the ability of a message to be presented in several formats. A real-life example...

4 minutes read.

How to Setup Environment for C++ Programming on Mac

Mac OS X code Installation There are so many environments available for C++. We are going to install jGrasp and Xcode in our mac operating system. Instruction for installation of jGrasp and...

2 minutes read.

Features of OOPS in C++

What is OOPs? The main reason programmers prefer C ++ language over C is because of the support of object-oriented programing in C++. As the name suggests, object-oriented programming or OOPs...

3 minutes read.