Input and Ouput in C++
Input and Output operations are typically handled through the use of the Standard Input/Output Library, which includes functions and objects for reading input and displaying output. Two primary streams, cin and cout, are used for input and output.
In C++, there are libraries that offer various methods for handling input and output. When we talk about input and output in C++, we are dealing with a flow of data organized as a sequence of bytes, commonly referred to as streams.
Input Stream: This term describes the flow of bytes from a device (like a keyboard) to the computer's main memory. In simpler terms, it's the process of receiving data.
Output Stream: On the other hand, an output stream refers to the flow of bytes in the opposite direction—from the computer's main memory to a device, such as the display screen. In more straightforward language, it's the process of sending data out.
cout is the primary output stream in C++, used for displaying output to the user.
Output Function
Output functions are used to display information to the user or to output data to a file or other devices. The primary output function in C++ is associated with the standard output stream, cout, which stands for "character output." It is part of the iostream library.
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
In this example, the text "Hello, World!" is sent to the standard output (typically the console or terminal).
The "<<" operator is used with cout to concatenate and display information. The endl is used to insert a newline character, moving the cursor to the next line.
Input Function
The primary input function is associated with the standard input stream, cin, which stands for "character input." It is part of the iostream library and is used for reading input from the user or other sources.
cin is the primary input stream in C++, used for reading input from the user or other input sources.
using namespace std;
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
cout << "You entered: " << number << endl;
return 0;
}
In this example, cin is used to read an integer entered by the user.
The >> operator is used with cin to extract and store input into variables.