Input/output operations are the operations through which a program receives data or displays results. These operations should be viewed from the program's perspective
Practically, the data that enters the program or leaves the program are strings of characters that the program receives or sends
The C++ language offers a uniform way to perform input/output operations, whether they are done on the console, in files, or with other devices that process characters.
This is called a stream. A stream can be viewed as a sequence of characters that are sent in a well-determined order from a source to a destination. The program will insert characters into the stream (if it is an output stream, which displays data) or will extract characters from the stream (if it is an input stream, from which data is read).
Next, we will talk about cout and cin – the standard output and input streams.
In most cases, the standard output device is the screen and can be accessed with the cout stream. For this, cout is used together with the insertion operator "<<" followed by the data to be displayed:
cout << "Hello"; // displays Hello on the screen
cout << 17; // displays the number 17 on the screen
cout << n; // displays the value of the variable n on the screen
In most cases, the standard input device is the keyboard and can be accessed with the cin stream. For this, cin is used together with the extraction operator ">>", followed by the variable in which the extracted value will be stored (the variable to be read):
int n;
cin >> n;
First, the variable n is declared, then a value is read for it – a value is extracted from cin and stored in the variable n. When running, the program waits for a value to be entered from the keyboard. In fact, the characters entered are transmitted to the program only when the ENTER key is pressed.
Standard input/output operations are done with the keyboard and screen, but it is also possible to perform readings from text files and writings to text files. To perform the actual operations, the files are associated with data streams, and the operations are similar to those with the keyboard and screen.
ifstream fin("INPUT_FILE_NAME");
ofstream fout("OUTPUT_FILE_NAME");
int x;
fin >> x;
fout << 2 * x;
fin.close();
fout.close();
In this section you can generate a summary of the page content using AI! Feel free to use the button below whenever you are in a hurry and don't have time to learn everything!
In this section you can ask our expert robot anything related to the questions you encountered during the lessons! Feel free to use the button below whenever you need additional explanations!