The C++ std::istream::getline() function is used to read a line of text from an input stream into a string or character array. It stops reading when it encounters a newline character or reaches the specified maximum number of characters, whichever comes first. The newline character is extracted but not stored.
SyntaxIt is useful for handling input that may contain spaces or other whitespace characters,as it captures the entire line.
Following is the syntax for std::istream::getline() function.
istream& getline (char* s, streamsize n ); istream& getline (char* s, streamsize n, char delim );Parameters
This function returns the basic_istream object (*this).
ExceptionsIf an exception is thrown, the object is in a valid state.
Data racesModifies the elements in the array pointed by s and the stream object.
ExampleIn the following example, we are going to consider the basic usage of the getline() function.
#include <iostream> int main() { char x[20]; std::cout << "Enter a line of text: "; std::cin.getline(x, 20); std::cout << "Entered Input : " << x << std::endl; return 0; }Output
Output of the above code is as follows −
Enter a line of text: Hello, Namaste Entered Input : Hello, NamasteExample
Consider the following example, where we are going to handle the empty input.
#include <iostream> int main() { char buffer[10]; std::cout << "Enter a text or press Enter : "; std::cin.getline(buffer, 10); if (buffer[0] == '\0') { std::cout << "No Input Provided." << std::endl; } else { std::cout << "Entered Input : " << buffer << std::endl; } return 0; }Output
Following is the output of the above code −
Enter a text or press Enter : No Input Provided.
istream.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4