We use the Stream concept. Think of a stream as a "conveyor belt" of data flowing either into your program (Input) or out of it (Output).
The two main tools we use are cin and cout, both of which live in the <iostream> library.
1. Standard Output (cout)
Purpose: To print text or variables to the screen.
Operator: Uses the Insertion Operator (
<<).Syntax:
cout << "Text" << variable;New Lines: Use
endlor\nto move the cursor to the next line.
2. Standard Input (cin)
Purpose: To read data from the keyboard and store it in a variable.
Operator: Uses the Extraction Operator (
>>).Mnemonic: Think of the arrows pointing into the variable.
Syntax:
cin >> myVariable;
Code Example: Making an Interactive Profile
This program asks the user for their information and then prints it back to them.
#include <iostream>
#include <string>
using namespace std;
int main() {
// 1. Declare variables to hold user input
string userName;
int userAge;
double userGpa;
// 2. Prompting the user (Output)
cout << "--- User Registration ---" << endl;
cout << "Enter your first name: ";
cin >> userName; // Extracts input into the variable
cout << "Enter your age: ";
cin >> userAge;
cout << "Enter your GPA: ";
cin >> userGpa;
// 3. Displaying the collected data (Output)
cout << "\n--- Account Summary ---" << endl;
cout << "Hello, " << userName << "!" << endl;
cout << "Age: " << userAge << " years old." << endl;
cout << "GPA: " << userGpa << endl;
return 0;
}Pro Tip: Handling Spaces in Strings
The standard cin >> userName; stops reading as soon as it hits a space. If you want to read a full name (like "John Doe"), you should use the getline() function instead:
string fullName;
cout << "Enter full name: ";
getline(cin >> ws, fullName); // 'ws' skips any leading whitespaces