Open In App

How to Read a Line of Input Text in C++?

Last Updated : 01 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, we often need to take input from the user by reading an input text line by line but the cin method only takes input till whilespace. In this article, we will look at how to read a full line of input in C++.

For Example,

Input: This is a text.
Output: Entered Text: This is a text.

Taking a Line of Input Text in C++

To read the complete line of text from the input stream, we can use the inbuilt function std::getline() that takes the input until either the end of input is reached or cin signals an error. The std::getline() function is specially used to read lines of input from the stream.

C++ Program to Read a Line of Input Text

C++




// C++ program to read a line of input text
  
#include <iostream>
#include <string>
using namespace std;
  
int main()
{
    // Declare a string to store the input
    string input;
  
    // Prompt the user to enter a line of text
    cout << "Enter a line of text: ";
  
    // Use getline() to read a line of text and store it in
    // the 'input' variable
    getline(cin, input);
  
    // Display the input
    cout << "You entered: " << input << endl;
  
    return 0;
}


Output

Enter a line of text: Hey! geek welcome to gfg
You entered: Hey! geek welcome to gfg

Note: By default, the delimiter is a new line(‘\n’) but we can also provide other delimiters that we want as a third parameter to the getline function.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads