MODULE 8
Input and Output in C++
Input and output (I/O) operations are essential for any programming language,
and C++ provides a comprehensive set of tools for performing I/O operations.
In C++, you can perform I/O using the Standard Input and Output Streams,
which are part of the C++ Standard Library (iostream). Here, is an overview of
basic input and output operations in C++.
Input (Reading User Input)
For reading user input, you can use the std::cin object, which is also part of the
std namespace. You use the >> operator to extract data from the standard input
stream.
Breakdown explanation from the above snipaste;
std::cin is the standard input stream.
>> is the extraction operator, used to read data from the stream.
int number; declares an integer variable to store the user's input.
"Enter a number: " is a prompt displayed to the user.
std::cin >> number; reads an integer value from the user.
std::cout << "You entered: " << number << std::endl; displays the entered
value.
Output (Displaying Information)
To display information to the console, you typically use the std::cout object,
which is part of the std namespace. You can use the << operator to send data to
the standard output stream.
Example:
Breakdown explanation from the above snipaste:
std::cout is the standard output stream.
<< is the insertion operator, which is used to send data to the stream.
"Hello, World!" is the data (in this case, a string) that you want to
display.
std::endl is used to insert a newline character and flush the output buffer.
Control Structures in C++
In the previous lectures we have said lots on the control structure as the
fundamental elements in C++ programming that allow you to control the flow
of your program. Here are some common control structures in C++:
if-else Statements
Conditional statements that allow you to execute different blocks of code based
on a specified condition.
Example;
while Loop
A loop that continues to execute a block of code as long as a specified condition
is true.
Example;
for Loop
A loop that executes a block of code for a specific number of iterations.
Example;
switch Statement
Used to select one of many code blocks to be executed.
Example;
do-while Loop
A loop that executes a block of code at least once and then continues to execute
as long as a specified condition is true.
Example;