×

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++ Continue in for loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the start...

4 minutes read.

C++ History

C++ is a middle-level programming language developed in 1980s by Bjarne Stroustrup at Bel Labs. C ++ development initially started in 1979, four years before its launch. It is started with...

1 minute read.

Exception Handling in C++ vs Java

Nowadays, exception handling is a feature found in virtually all object-oriented languages. We can also find this type of feature in Java and C++. The try-catch and block is required...

3 minutes read.

C++ Deque

Definition: Deque or the Doubly ended queue is a data structure or operation performed under queue where insertion and deletion are allowed at both ends. A deque is an ordered collection of...

5 minutes read.

C++ Identifier

In a program, C++ identifiers relate to the names of variables, functions, arrays, and other user-defined data types that the programmer has developed. They are a prerequisite for learning any...

4 minutes read.

Converting string into integer in C++

When programming in C++, we'll frequently need to change one data type to another. When we use C++ to create apps, we must transform data from one type to another. When...

7 minutes read.

Skyline Problem in C++

We have given n rectangular buildings in a 2-dimensional city. Here, to compute the Skyline of the given n rectangle structures in a two-dimensional metropolis while removing hidden lines, the...

3 minutes read.

abs() function in C++

In C++, the abs() function returns the absolute value of any integer number. Using this function a negative integer is multiplied by -1 and positive number or zero is returned...

4 minutes read.

C ++ Program: Alphabet Triangle and Number Triangle

Alphabet Triangle and Number Triangle An alphabet triangle is a triangle that typically looks like a pyramid or other triangles like an isosceles triangle, a right-angled triangle consisting of similar or...

4 minutes read.

Nullptr in C++

What is Nullptr in C++? A null pointer value is represented by the term nullptr. Use a null pointer value to indicate that a native pointer type, inner pointer, or object...

3 minutes read.

How to initialize a dynamic array in C++

Regular arrays or static arrays have a predetermined size or fixed size. Change in the size of regular arrays is not possible. The memory size for static arrays determines at compile...

4 minutes read.

Pointer to Object in C++

What is a pointer? A pointer in C++ is used to point the variable by storing the address of the variable. In C++, to print the address of the variable, we...

4 minutes read.

Divide by Zero Exception in C++

We use exception handling method to handle the divide by zero exception. Dividing a number with zero is generally mathematical error. We have to exception handling method to overcome this...

2 minutes read.

Dynamic _Cast in C++

C++ is one of the most powerful programming languages. We can write object-oriented and structured programming with the help of C++. In this article, we will learn about the dynamic...

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

C++ Encapsulation

The following two essential components are present in all C++ programmes: Functions are the parts of a programme that perform actions, and they are termed programme statements (code).Program data is the...

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

Palindrome Number Program in C++

A palindrome number is one that is the same when it is reversed. Palindrome numbers include 22, 33, 44, 55, 66, 77, 88, and 99. Algorithm for Palindrome Numbers Get the user's...

4 minutes read.

Snake Code in C++

Snake is a popular game that can be played on almost any device and runs on any operating system. In this game, snakes can move in any direction, including left,...

4 minutes read.

Factorial Program in C++

C++ Factorial Program: The product of all positive descending integers is the factorial of n. n! denotes the factorial of n. For instance: 5! = 5*4*3*2*1=120 4! = 4*3*2*1=24 In Combinations and Permutations, the...

4 minutes read.