GETLINE()

The getline() function is used to read an entire line of text, including spaces, from an input stream into a std::string variable. It works with any input stream, such as std::cin for user input or std::ifstream for reading from a file. Unlike the >> extraction operator, which stops reading at whitespace, getline() continues until it encounters a newline character (\n) or the end of the file (EOF). This makes it ideal for reading input that may contain spaces, such as full names, sentences, or lines of text in a file.

When reading from a file using std::getline(std::ifstream& is, std::string& str), the function will read one line at a time from the file, discarding the newline character and storing the content in the string. getline() is specifically designed for reading text data, not numeric types, so it is particularly useful for processing lines of text, whether from user input or files, where the content may include spaces or other non-delimited characters.


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

 * istream is often cin
 * string is where the line is stored
 * delim is an optional custom delimiter (defaults to newline \n), allowing control 
   over how input is parsed
#include <iostream>
#include <string>
using namespace std;

int main()
{
  string name;
  cout << "Enter your full name: ";
  getline(cin, name);
  cout << "Hello, " << name << "!" << endl;
  return 0;
}

Last updated