C++ Getline - C++ Programming Tutorial
C++ Course / Miscellaneous / C++ Getline

C++ Getline

BLUF: Mastering C++ Getline is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: C++ Getline

C++ is renowned for its efficiency. Learn how C++ Getline enables low-level control and high-performance computing in the tutorial below.

In C++, the getline function is a predefined function specified in the <string> header file. It facilitates the extraction of an entire line of text from an input stream. While cin is an object utilized for user input, it restricts input to single lines only.

We utilize the getline function to receive input spanning multiple lines. This function allows for capturing an entire line, including spaces, enhancing its utility for managing intricate input situations within C++.

Syntax of getline function:

1. The first way of declaring is to pass three parameters.

Example

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

The syntax mentioned above includes three parameters: namely, is, str, and delim.

Where,

It represents an instance of the istream class specifying the source for reading the input stream.

str: It is a data type that stores a sequence of characters within a variable.

delim: It is the delimiting character.

Return value

This function provides the input stream object, which is supplied as an argument to the function.

2. The second way of declaring is to pass two parameters.

Example

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

The preceding syntax includes two arguments, namely, is and str. This format closely resembles the previous syntax with the exception of lacking any delimiter characters.

Where,

is: It represents an object belonging to the istream class, specifying the source from which the input stream is to be read.

str: It represents a string object that stores textual data.

Return value

This function additionally provides the input stream, which is supplied as an argument to the function.

C++ getline Function Example:

Let's consider a basic scenario where we capture user input without relying on the getline function.

Example

Example

#include <iostream>  

#include<string.h>  

using namespace std;  //using standard namespace

int main()  //main function

{  

string name; // variable declaration  

std::cout << "Enter your name :" << std::endl;  

cin>>name;  

cout<<"\nHello "<<name;  

return 0;  

}

Output:

Output

Enter your name :

John Miller

Hello John

Explanation:

In this instance, we acquire user input utilizing the cin>>name statement without employing the getline function. Subsequently, 'John Miller' was entered as the user input, yet solely 'John' was visible. Hence, we infer that cin disregards characters following a space character.

Let's address the aforementioned issue by employing the getline function.

Example

Example

#include <iostream>  

#include<string.h>  

using namespace std;  //using standard namespace

int main()  //main function

{  

string name; // variable declaration.  

std::cout << "Enter your name :" << std::endl;  

getline(cin,name); // implementing a getline() function  

cout<<"\nHello "<<name;  

return 0;

}

Output:

Output

Enter your name :

John Miller

Hello John Miller

Explanation:

In the preceding code snippet, we've employed the getline method to capture characters, including spaces. Upon execution, we can note that both terms, specifically John and Miller, are presented, indicating that getline includes characters following spaces.

Using the getline with a Delimiter to Stop Input at a Space in C++

Example

Example

#include <iostream>  

#include<string.h>  

using namespace std;  

int main()  

{  

string profile; // variable declaration  

std::cout << "Enter your profile :" << std::endl;  

getline(cin,profile,' '); // implementing getline() function with a delimiting character.  

cout<<"\nProfile is :"<<profile;  

}

Output:

Output

Enter your profile :

Software Developer

The profile is: Software

Explanation:

In the provided code snippet, we obtain the user input utilizing the getline function. In this scenario, we introduce the delimiting character('') within a third argument. In this case, the delimiting character is a space character, signifying that any character following a space will be disregarded.

Using C++ getline with Two Parameters:

In C++, the getline method reads input until encountering a newline (\n) character as its default behavior. It saves the input within the specified string variable. This particular usage of getline is widely adopted for reading complete lines of text efficiently.

Syntax:

It has the following syntax:

Example

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

C++ Getline function Example using two parameters:

Example

Example

#include <iostream>

#include <string>

using namespace std;

int main() {

    string fullName;

    cout << "Enter your full name: ";

    getline(cin, fullName);

    cout << "Hello, " << fullName << "!" << endl;

    return 0;

}

Output:

Output

Enter your full name: John Smith

Hello, John Smith!

Explanation:

In this instance, the user is prompted to input their complete name. Subsequently, the getline (cin, full name) method captures the entire input, spaces included (for instance, "Alice Johnson"). Lastly, the program offers a greeting to the user utilizing their full name.

Using C++ getline with Three Parameters:

The three-argument form of Getline enables us to define a custom delimiter besides the standard Newline (\n). This comes in handy when differentiating data fields using unique characters like a comma, semicolon, or pipe symbol.

Syntax:

It has the following syntax:

Example

getline(input_stream, destination_string, delimiter_char);

C++ Getline function Example using three parameters:

Example

Example

#include <iostream>

#include <string>

using namespace std;

int main() {

    string data;

    cout << "Enter some text ending with a '#': ";

    getline(cin, data, '#');  // Using getline with delimiter '#'

    cout << "You entered: " << data << endl;

    return 0;

}

Output:

Output

Enter some text ending with a '#': Hello World, this is C++ Getline #

You entered: Hello World, this is C++ Getline

Explanation:

This C++ program reads user input until encountering the # character, which is excluded from the final stored string.

Getline Character Array:

We can alternatively implement the getline function for character arrays; however, its syntax varies from the previous method.

Syntax:

It has the following syntax:

Example

istream& getline(char* , int size);

In the given syntax, there are two arguments: char* for character pointers, and size for specifying the size of data.

Where,

  • char*: This denotes a character pointer that points to the beginning of the array.
  • Size: This serves as a boundary that specifies the maximum size the array can accommodate, preventing input from exceeding this limit.
  • C++ Getline Character Array Example:

    Example

Example

#include <iostream>  

#include<string.h>  

using namespace std;  

int main()  

{  

char fruits[50]; // array declaration  

cout<< "Enter your favourite fruit: ";  

cin.getline(fruits, 50); // implementing the getline() function  

std::cout << "\nYour favorite fruit is :"<<fruits << std::endl;  

return 0;  

}

Output:

Output

Enter your favourite fruit: Watermelon

Your favorite fruit is Watermelon

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

Example

Example

#include <iostream>

using namespace std;

int main() {

    char str[10];

    cout << "Enter a string: ";

    cin.getline(str, 10);

    cout << "You entered: " << str << endl;

    return 0;

}

Output:

Output

Enter a string: HelloWorldAgain

You entered: HelloWorld

Explanation:

The cin. getline(str, 10) method reads a maximum of 9 characters and adds a null terminator (\0) at the end. If the input surpasses this limit, the additional characters remain in the input buffer, and only the permitted characters are saved.

Conclusion

In summary, the getline function in C++ proves to be a crucial utility for capturing complete lines of input, inclusive of spaces, be it within a std::string or a character array. It halts at whitespace characters and circumvents the limitations of cin boundaries.

C++ Getline function Multiple Choice Questions

  1. What does the getline function mainly do in C ++?
  • Reads a single word
  • reads a single character
  • reads a full line until a newline character
  • ignores spaces and reads till the end
  1. Which major limitation of cin does getline solve?
  • Reading numerical value
  • reading input with whitespaces
  • reading character arrays
  • Except unwanted inputs
  1. When using getline, what happens if the input stream already contains a newline character before calling it?
  • It generally reads new input
  • It leaves Newline and waits for new input
  • It immediately reads an empty string
  • This causes a compilation-time error
  1. What will happen if we specify a delimiter in the gateline ?
  • Getline will ignore it and stop at Newline
  • Getline will stop reading when it encounters that delimiter
  • This will cause a segmentation fault
  • It will continue to read until the buffer is complete
  1. Which of the following describes the best getline when it works with character arrays?
  • It reads the size of the array
  • It automatically gives array resize.
  • It reads up to a specified size or until a delimiter
  • It always leaves the first character

It stops at a defined size or a delimiter as specified in option c).

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience