Module (or as they say in the case of C – header) or header file iostream It is intended to provide input-output means, to the standard console. That is. then, that keyboard input and reading with a user screen.
It has all its features in the namespace std, therefore either have to ascribe a prefix for its use std, or specify a namespace through using namespace
1 2 3 4 | using namespace std; ... cin >> Переменная; cout << "Чет там"; |
Or
1 2 | std::cin >> Переменная; std::cout << "Чет там"; |
In this article, we will use the first option – namespace connectivity through using namespace.
iostream It comprises two main classes:
- cin – for processing keyboard input;
- cout – to display the console variables or just text;
There are classes Palau and clog, but in general, They are used not so often, and of which we will not mention. If you are interested – These classes are used to display errors in operations and logging activities.
I must say, that not all, that is inherent in these classes will be described. Only the most commonly used functionality of. This is the formatted output redirection operators (<< and >>), are engaged in output variables depending on their type and the specified format. This operators unformatted read write (read: feet of my house or posimvolьno), methods get(), put() and write() designed to simply display an array of characters whatever they were. And the formatting operators setf(), width(), precision(), which indicate the current output, how to format the displayed, how to align it, which side and how to put characters after the decimal point.
class cin
Loop cin It contains a variety of methods. All they can see, if you enter a keyword in the development environment cin and put it after point. The Code Editor will offer all available methods in this class to choose from:
As stated above, for beginners, we will look at only some of them.
Loop cin based on class istream, and includes the ability to input redirection. Using operator overloading >> , class allows you to specify what variable will be input.
1 2 3 4 5 | double d; int i; string s; cin >> d >> i >> s; |
These variables obtained in Example (read) his data according to their positions in the operation. In this example, first read in real d, then a whole in i, and then a string variable. It is necessary to consider – wrong sequence variables can give any input error, or variables can get the data they are not targeting.
When reading the lines need to remember, that if it will meet the gap, Proofreading is complete (the operating system parameters are taken to separate spaces). So convenient to split a string into words. To illustrate this can be such an example:
1 2 3 4 5 6 7 8 9 10 | #include <iostream> #include <string> using namespace std; int main() { string s; for (cin >> s; !cin.eof(); cin >> s) cout << s << endl; } |
From personal experience, I recommend not to use just such a line dividing the method into words, but be aware of this is helpful.
If you need to consider the entire string to the transfer carriage, It is to use the method discussed below getline().
Method get()
It allows you to enter a character or a string. When entering drains supports separator, said programmer, to which will be read line. The default is a newline 'n' That is the method get() waiting press Enter-key. Only then handles readable.
When you enter a character in the numeric variable, method returns the code for this symbol:
1 2 | int c = cin.get(); // Получаем код символа char c = cin.get(); // Или сам символ |
cin.get() often put at the end of the program, to hold the console with the results:
1 2 3 4 | ...... cin.get(); return 0 } |
In classic C is a popular analogue function getchar() for the delay.
To make using this method the line input, enough to pass in its parameters a pointer to an array of characters, where you want to record, and the number of symbols, which is expected to enter.
1 2 3 4 5 6 7 8 9 | int n = 10; char *s = new char[n]; cout << "\nВведите строку из 10 символов: "; cin.get(s,n); cout << "Строка: " << s << endl; delete [] s; //Остальное, если строку ввели в размере более n символов - отсекаем (игнорируем) сin.ignore(); |
The scheme is simple: A pointer to an array of characters, transfer the number to be read, and after pressing the Enter-key, cin.get() said array is in the predetermined number of symbols. The remaining characters are not retrieved, so to get rid of them, you can call the input buffer method ignore().
If you specify the third parameter delimiter, cin.get() It will read either as ordered symbols, or until cin not meet this symbol:
1 | cin.get(s,n,' '); |
Here in s a string code is read until the first gap. If the gap is not found – will either read before pressing Enter-or to n-e have many symbols.
Method getline()
Same method get(). Among, what “can” get(), redefined for the type of lines string. As well as get() able to read characters, specified as delimiter, as the first parameter specifies an array of characters, a second number of symbols to be read.
Using it redefined version in Cheder string looks like that:
1 2 | string s; getline(cin,s); |
Класс cost
Loop cout It involves data output to the console. The base class ostream. The main operator – overloaded << He points, which variable output to the console.
1 2 3 4 5 | double d = 1; int i = 2; string s = "123"; cout << d << i << s; |
The rules are the same sequence, that cin – the output from left to right.
it is recommended to use the operator for a carriage return on a new line endl. Or to transfer a good old ‘n’
1 | cout << d << i << s << endl; |
1 | cout << d << i << s << '\n'; |
Method put() displays a symbol in the console:
1 | cout.put('В'); |
Outputs one character.
Method write() displays the symbol block from the array of characters, referred to it as a pointer
1 2 3 4 5 6 7 8 9 10 | #include <iostream> using namespace std; int main() { char *s = "Hello"; cout.write(s, strlen(s)); cout << endl; cout.write(s, 2); cout << endl; } |
Basically, in write() You can pass a pointer to any memory unit, but for output to the console is characterized only read arrays, human-readable characters.
Method width() sets the width of output, if necessary to level up to a certain number of symbols. Typically used in the tables. A typical example of: The derivation of the calculation table (example below).
Method precision() It indicates how many digits in the fractional part will be, if displayed real variable.
Method setf() determines, as will be align (to the left, to the right, at the center) derivable, and in which format it is.
A comprehensive example of these techniques can be seen in the task of constructing a parabola table:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include <iostream> using namespace std; int main() { setlocale(LC_ALL, "rus"); double x; // Указываем дополнить слово "Парабола" до 15 символов пробелами cout.width(15); cout << "Парабола" << endl; // Указываем дополнить слово "Х" до 10 символов пробелами cout.width(10); cout << "X" << endl; // Указываем дополнить слово "Y" до 10 символов пробелами cout.width(10); cout << "Y" << endl; // Указываем что выравниваться выводимое будет справа // Т.е. пробелы дополнятся слева cout.setf(ios::right); for (x = 0; x < 10; x += 1){ cout.width(10); cout << x << '|'; cout.width(10); cout << x*x << '|' << endl; }; } |
16-hexadecimal representation of a string can be derived, for example, like this :
1 2 3 4 5 6 7 8 9 10 11 | #include <iostream> using namespace std; int main() { char *s = "figaro"; cout.setf(ios::hex, ios::basefield); for (int i = 0; s[i]; i++) cout << (int)s[i] << ' '; cout << endl; } |
And so the scientific format for real:
1 2 3 4 5 6 7 8 | #include <iostream> using namespace std; int main() { cout.setf(ios::scientific); cout << 123.456; cout << endl; } |
You can set the output format of Boolean variables:
1 2 3 4 5 6 7 8 | #include <iostream> using namespace std; int main() { cout << false << endl;//Выведет 0 - целый вид false cout.setf(ios::boolalpha); cout << false << endl; //Выведет строкой "false" } |
Work with the methods of these classes yourself. Try to understand, making each. This independent practice will be very useful.
Newsletter of programming: |
ignore method().
And the SETF formatting operators(), width(), precision(),
and so on. What a translation?