C++ User Input: Building Interactive Programs
How to gather data and interact with the user via the console.
What is I/O in C++?
I/O stands for Input/Output. In C++, we use two primary objects for this: cout for displaying information and cin for receiving it. These objects are part of the standard library and are essential for any interactive application.
Basic Syntax for I/O
Let's take a look at how to use these objects in a real-world scenario. Notice the extraction (>>) and insertion (<<) operators:
int age;
cout << "Enter your age: "; // Insertion: Data flows to console
cin >> age; // Extraction: Data flows from keyboard
cout << "You are " << age << " years old.";
Handling Strings
For single words, cin works perfectly. However, for full names or phrases with spaces, you should use the getline() function to ensure that the entire line is captured correctly.
Note: Always include the <string> header if you're using the string data type for user input.
Practice Exercise: Step 3
Combine your knowledge of Data Types and Input! Create a program that takes a user's name and age as input, then displays a personalized greeting.