Table of Contents
The extraction operator (>>) reads input only until the first whitespace character is encountered. To read an entire line of text, including spaces, the std::getline() function is used.
This example demonstrates how to read a complete line of input from the standard input stream.
Source Code #
#include <iostream>
#include <string>
int main()
{
std::string name;
std::cout << "Enter your full name: ";
std::getline(std::cin, name);
std::cout << "Name: " << name << '\n';
return 0;
}
Output #
Enter your full name: John Smith
Name: John Smith
Explanation #
#include <string>includes the Standard Library header that defines thestd::stringclass.std::string name;declares a string object capable of storing a sequence of characters.std::getline(std::cin, name);reads characters from the standard input stream until a newline character is encountered.- Unlike the extraction operator (
>>),std::getline()preserves spaces entered by the user. - The newline character used to terminate the input is extracted from the input stream but is not stored in the string.
std::cout << "Name: " << name << '\n';displays the complete line stored in the string object.return 0;terminates the program successfully.