1.4) Input and output in C++
Input and output (I/O) are essential aspects of programming, allowing you to interact with the user and display information. C++ provides the iostream library for handling I/O operations.
Let’s explore input and output in detail with code examples and explanations.
Table of Contents
Output with cout
The cout (character output) stream is used to display information to the console.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl; // Output text
int age = 25;
cout << "My age is " << age << " years." << endl; // Output variable
return 0;
}
Output:
Hello, World!
My age is 25 years.
Explanation:
cout << ...
is used to output data to the console.<<
is the stream insertion operator.endl
is used to insert a newline and flush the output buffer.
Input with cin
The cin
(character input) stream is used to read data from the user.
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter a number: ";
cin >> num; // Read user input
cout << "You entered: " << num << endl;
return 0;
}
Input:
Enter a number: 42
Output:
You entered: 42
Explanation:
cin >> num
reads user input and assigns it to thenum
variable.- The program prompts the user to enter a number, and then displays the entered value.
Formatted Output
You can use formatting options to control how data is displayed.
#include <iostream>
#include <iomanip> // Include for formatting
using namespace std;
int main() {
double value = 123.456;
cout << fixed << setprecision(2); // Formatting options
cout << "Formatted value: " << value << endl;
return 0;
}
Output:
Formatted value: 123.46
Explanation:
fixed
ensures that the number is displayed with a fixed number of decimal places.setprecision(2)
sets the number of decimal places to 2.
Reading Strings with getline
To read an entire line of text including spaces, use getline()
.
#include <iostream>
using namespace std;
int main() {
string name;
cout << "Enter your name: ";
getline(cin, name); // Read entire line
cout << "Hello, " << name << "!" << endl;
return 0;
}
Input:
Enter your name: John Doe
Output:
Hello, John Doe!
Explanation:
getline(cin, name)
reads an entire line from the user input and stores it in thename
variable.
These examples showcase the use of cout
for output and cin
for input, as well as some formatting options. Understanding input and output is crucial for creating interactive and user-friendly programs in C++.