Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Getline Function in C++

Last Updated on October 17, 2023 by Ankit Kochar

In the world of C++ programming, handling user input from the console is a fundamental task. The getline function is a versatile and powerful tool that allows you to read input from the user as a string, making it an essential part of any C++ developer’s toolkit. This article delves into the getline function in C++, explaining its usage, advantages, and common pitfalls to help you master this critical aspect of input processing in C++. Let’s see what is and how to use getline in C++.

What is getline Function C++?

getline is a function in C++ that is used to read a line of text from an input stream, such as cin, into a string. The function is part of the standard library and is declared in the string header. The basic syntax for using getline function c++ is as follows:

string str;
getline(cin, str);

The first argument of getline function c++ is the input stream from which you want to read the data, and the second argument is the string object where the data will be stored. The function reads the input stream until it encounters a newline character (‘\n’), at which point it stops reading and returns the contents of the input stream as a string.
Getline function c++ is particularly useful when you need to read an entire line of text, rather than just a single word, from the user. For example, you might use the getline function c++ to read a line of text from the user and store it in a string for later processing.

Syntax of getline Function in C++

We can declare getline function c++ by following two syntaxes. Both of the syntaxes have their own use and application so the user can use them according to its requirement. The two syntaxes vary on the number of parameters used in them, one has three parameters used in it and the other has three parameters used in it.

Using Three Parameters
Here you can represent, the getline function c++ by using three variables.
The general syntax for the getline function c++ with three parameters is

istream& getline (istream& is, string& str, char delimiting);

The istream& getline is used to define the function in c++ and the rest three are parameters.

  • is: This is the input stream object and defines the location so that it can be used to read the stream.
  • str: In this object, we will store the line or string that we have read.
  • delimiting: the delimiter character that separates the input stream into lines. By default, the delimiter is the newline character (‘\n’).

Using Two Parameters
Here you can represent, the getline function c++ by using two variables.

istream& getline( istream& is, string& str );

The istream&getline is used for defining the function in c++ and the other two parameters are:

  • is: This is the input stream object and defines the location so that it can be used to read the stream.
  • str: In this object, we will store the line or string that we have read.

Return Value
No matter the syntax you used the getline function c++ will return the input stream that the user has passed as an argument to the function.

Examples of getline Function C++

Before directly moving to the example of getline function c++ first we will look at an example of cin and see the problem that occurred there.

Example: Using cin
In this example we will use the cin function in c++ to take the input.

#include <iostream>
#include<string.h>
using namespace std;

int main(){

    string user_name; 

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

    cin>>user_name;  


    cout<<"\nWelcome to PrepBytes "<<user_name;

    return 0;

}

Input

Naman Kukreja

Output

What is your name? :

Welcome to PrepBytes Naman

Explanation of the above code
As you can see in the result, the user’s first name was the only thing that was shown. This is due to the fact that the compiler terminated its scanning of the input stream the moment it reached a space (" "). Thus, it is clear that the cin object is unable to read input that contains several words or lines. You must utilize the getline function c++ for this reason.

Example: Using Two Parameters
Here we will use the getline function c++ and with the help of that we can print the whole name of the user that we were not able to achieve because of using cin. By using two parameters we are not using the delimiting character.

#include <iostream>

#include<string.h>

using namespace std;

int main(){

    string user_name; 

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

    getline(cin, user_name);

    cout<<"\nWelcome to PrepBytes "<<user_name;

    return 0;

}

Input

Vikas Sharma

Output

What is your name? :

Welcome to PrepBytes Vikas Sharma

Explanation of the above example
In this example, you have seen now the full name is printing this is because we are using the getline function c++ with two parameters.

Example: Using Three Parameters
A delimiting character can also be used to prevent the getline function c++ from continuing to read the input stream after it meets that character. Use the space (" ") as a delimiting character to stop the function from reading the final name after the space to see that in action. As a result, it will produce the same results as when you utilized the cin object.

#include 

#include

using namespace std;

int main(){

    string user_name;   

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

    getline(cin, user_name, ' ');

    cout<<"\nWelcome to PrepBytes "<<user_name;

    return 0;

}

Input

Harsh Yadav

Output

What is your name? :

Welcome to PrepBytes Harsh

Explanation of the above example
As you can see, even though the getline function c++ was used, the result only showed the first name since the space character was used as a delimiting character.

Getline Function C++ with a Character Array

You can also use the getline function c++ for a character array but the syntax will not be the same as you have seen above it will vary a little bit the syntax of the getline function c++ for character array is

istream& getline(char* , int size);

There are two parameters in the above syntax and they refer to

  • char: It is the character pointer that will be pointing to the character array.
  • int size: This specifies the array’s maximum size. Since going beyond the limit would cause the reading to halt, it serves as the delimiter.

Example
Here we will use the getline function c++ for a character array.

#include <iostream>

#include<string.h>

using namespace std;

int main(){  

    char phone[50]; 

    cout<< "Enter the name of some Phone Brands: ";   

    cin.getline(phone, 50);

    cout << "\nPhones list :"<<phone << endl;

    return 0;

}

Input

Samsung, Apple, Oppo, OnePlus

Output
Enter the name of some Phone Brands:
Phones list :Samsung, Apple, Oppo, OnePlus
Explanation of the above code
In the above example we have seen that all the elements we have entered in the character array are shown in the output and when we enter beyond the limit it will not read beyond the specified limit.

Application of getline Function C++

The getline function C++ has several applications, including

  • Reading input from the standard input stream (cin): You can use getline function c++ to read an entire line of text from the standard input stream, which is often useful for reading user input from the keyboard.
  • Reading data from a file: getline function c++ can be used to read text data from a file, one line at a time. This is useful for processing large files line by line, without having to read the entire file into memory at once.
  • Parsing strings: getline function c++ can be used to extract specific data from a string. For example, you could use getline function c++ to extract individual fields from a comma-separated values (CSV) file.
  • Processing text data: getline can be used to process text data from a variety of sources, including user input, files, and strings. For example, you could use getline function c++ to extract information from a log file, or to process text data from a database.
  • String manipulation: getline can be used to manipulate strings by reading individual lines of text and processing them as necessary. For example, you could use getline to extract specific words or phrases from a string and store them in a separate data structure.

Overall, the getline function c++ is a versatile function that can be used in a variety of contexts to process and manipulate text data in C++.

Advantages of using the getline Function C++

  • Std::getline function c++ can read a line of text including spaces, which is not possible with cin alone.
  • It can handle any type of input stream, not just cin.
  • You can specify the maximum number of characters to be read, avoiding buffer overflow issues.
  • It can be used to parse CSV (Comma Separated Value) files or any other text file that has lines separated by a specific delimiter.
  • You can use std::getline function c++ to read a line of text into a std::string, which can be easier to work with than a character array.

Disadvantages of using the getline Function C++

  • It can be slower than cin for reading single values because it has to process the entire line of text.
  • It does not allow you to specify the delimiter used to separate the values, so you may need to use other functions to extract specific values from the input.
  • std::getline function c++ does not automatically skip leading whitespace characters, so you may need to add code to handle that manually.
  • It can lead to unexpected behavior if the input contains more characters than the specified maximum length.
  • It may not be the best choice for reading binary data, as it reads the data as text and may introduce unexpected characters or change the representation of the data.

Conclusion
The getline function in C++ is a versatile tool that simplifies the task of reading lines of text from various input sources. Its ability to capture entire lines, including spaces, makes it indispensable for handling user input and text file processing. Whether you’re building a console application or working with file input, understanding how to use getline is a valuable skill for C++ developers.

In conclusion, mastering the getline function enhances your ability to interact with users and process textual data effectively, contributing to the overall robustness and usability of your C++ programs.

Frequently Asked Questions Related to Getline Function in C++

Here are some FAQs related to Getline in C++.

1. Can getline be used with input from sources other than cin?
Yes, getline can be used with any input stream, such as files (ifstream) or custom input streams.

2. How do you handle empty lines when using getline?
getline reads empty lines as well. You can check if the resulting string is empty and decide how to handle it in your code.

3. What happens if the input line is longer than the string variable’s capacity?
If the input line exceeds the string’s capacity, the excess characters will be discarded, potentially leading to data loss. To avoid this, you can use getline with custom delimiters or read input in smaller chunks.

4. Are there any alternatives to getline for reading lines of text in C++?
Yes, you can also use the gets function or the std::getline function from the header for reading lines of text in C++. However, getline from the header is recommended for safety and convenience reasons.

Leave a Reply

Your email address will not be published. Required fields are marked *