×

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 For FCFS (First Come First Serve)

The most basic scheduling technique is FCFS, often known as "FIFO (First In, First Out)". In this procedure, the first one is utilized and executed first, while the second one...

4 minutes read.

Static keyword in C++ vs Java

Both in C++ and Java, the static keyword is employed for essentially the same function. But there are some variations. The static keyword's similarities and differences between C++ and Java...

3 minutes read.

C++ Math Functions

C++ Math Functions: Like other programming languages, C++ offers plenty of mathematical functions needed for various purposes. These functions are defined mainly in the math library in C++. Let us...

4 minutes read.

C++ Range-based For Loop

In C++ language, the range-based for loop was added, which is far superior than the ordinary For loop. The implementation of a range-based for loop doesn't really need much code. It's a...

4 minutes read.

C++ Namespaces

An Overview In each scope, a name can only represent one entity. As a result, there cannot be two independent variables with the similar names in the same scope, as this may cause...

10 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.

C++ Virtual Function

A virtual function is such function which is declared inside the base class and redefined by the derive class. C++ uses a virtual keyword to make a function as a virtual function. The virtual...

1 minute read.

C++ Call by Value

In this article, we will discuss C++ Call by Value with their syntax, examples, use cases, advantages, and disadvantages. C++ Function A function is a set of statements that executes a task....

5 minutes read.

Quick Sort in C++

Quick sort is an efficient, in-place, comparison-based sorting algorithm that uses a divide-and-conquer strategy to sort an array or list of elements. First a pivot element is selected from the...

4 minutes read.

Pure Virtual Function in C++ With Example Program

What is a Virtual Function? A virtual function is created inside a class with the keyword virtual. A virtual function does not have any value to be returned. Once a virtual...

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.

Accumulate() and partial_sum() in C++ STL Numeric header

The C++ STL's numeric library includes the numeric header. This library provides efficient numeric arrays, support for random number generation, and fundamental mathematical operations and types. Several of the numeric...

3 minutes read.

Program to arrange an array in alternate positive and negative numbers

Let’s say, there is given an array arr, arrange the array in such a way that every positive number is followed by a negative number. If there are extra positive...

4 minutes read.

Constexpr in C++

Constexpr is a keyword in C++ that is used to declare variables or functions as compile-time constants. This means that the value of a constexpr variable or the return value...

3 minutes read.

C++ Bidirectional Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

Factorial of a Number in C++ using while Loop

What is a factorial? The factorial of a number is the product of all the positive numbers less than or equal to n, indicated by n! According to the standard for an...

6 minutes read.

Top 14 Best Free C++ IDE (Editor & Compiler) for Windows in 2024

Bjarne Stroustrup created the all-purpose object-oriented programming language C++. To develop C++ programs, there are various Integrated Development Environments (IDE) that offer prewritten code templates. These programs automatically modify the...

6 minutes read.

Single level Inheritance

Inheritance is a fundamental element of C++’s Object-Oriented Programming (OOP). It allows a class (called the derived class) to inherit characteristics and attributes from another class (called the base class)....

5 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.

C++ find missing in the second array

Given two arrays A and B of sizes n and m. Find the elements from array A that are not present in array B. Example Input : a[] = {1, 2, 3, 5,...

3 minutes read.