C++ Online Compiler
Example: Reading Entire Lines of User Input
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Reading Entire Lines of User Input #include
#include
using namespace std; int main() { // Step 1: Declare a string to store user input string fullName; string city; // Step 2: Prompt for full name and read it using getline() cout << "Please enter your full name: "; // getline(input_stream, string_variable) getline(cin, fullName); cout << "Hello, " << fullName << "!" << endl; // Step 3: Be careful with mixed cin and getline // If there's a leftover newline character in the buffer from a previous cin >>, // getline might read it immediately as an empty line. int age; cout << "Enter your age: "; cin >> age; // Clear the newline character from the input buffer cin.ignore(); // Discards characters up to and including the next newline cout << "Enter your city: "; getline(cin, city); // Now it will correctly read the city cout << "You are " << age << " years old and live in " << city << "." << endl; return 0; }
Output
Clear
ADVERTISEMENTS