Cin get c что это
Перейти к содержимому

Cin get c что это

  • автор:

 

How to use cin.get(), cin.peek() and cin.putback() in c++ programming.

First of all, we have to understand how we used to take input while working on a console-based app. We use cin>>var to take some var variable into our program. The variable can be of int, double, char or string type. But the question is how this input works?

So when we give input on running this program and suppose we give input as cplusplus then this input is stored in input buffer stream like this and pointer(arrow) is placed at the first buffer.

Note:- This is not the pointer which holds the address.

Since we are using char type variable so the first value is stored in the variable var as ‘c’ and the pointer move to the next input buffer i.e. ‘p’.

Now if we are using another cin statement in our program may be for a variable var1 of char data type then the next value in the input buffer stream is assigned to the variable var1.

Cin get c что это

The cin object in C++ is an object of class iostream. It is used to accept the input from the standard input device i.e. keyboard. It is associated with the standard C input stream stdin. The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator extracts the data from the object cin which is entered using the keyboard.

Program 1:

Below is the C++ program to implement cin object:

Input:

Output:

Program 2:

Multiple inputs using the extraction operators(>>) with cin. Below is the C++ program to take multiple user inputs:

Input:

Output:

The cin can also be used with some member functions which are as follows:

 

std:: istream::get

Extracts characters from the stream, as unformatted input:

(1) single character Extracts a single character from the stream.
The character is either returned (first signature), or set as the value of its argument (second signature). (2) c-string Extracts characters from the stream and stores them in s as a c-string, until either (n-1) characters have been extracted or the delimiting character is encountered: the being either the newline character ( ‘\n’ ) or delim (if this argument is specified).
The delimiting character is not extracted from the input sequence if found, and remains there as the next character to be extracted from the stream (see getline for an alternative that does discard the delimiting character).
A null character ( ‘\0’ ) is automatically appended to the written sequence if n is greater than zero, even if an empty string is extracted.
(3) stream buffer Extracts characters from the stream and inserts them into the output sequence controlled by the stream buffer object sb , stopping either as soon as such an insertion fails or as soon as the delimiting character is encountered in the input sequence (the being either the newline character, ‘\n’ , or delim , if this argument is specified).
Only the characters successfully inserted into sb are extracted from the stream: Neither the delimiting character, nor eventually the character that failed to be inserted at sb , are extracted from the input sequence and remain there as the next character to be extracted from the stream.

The function also stops extracting characters if the end-of-file is reached. If this is reached prematurely (before meeting the conditions described above), the function sets the eofbit flag.

Internally, the function accesses the input sequence by first constructing a sentry object (with noskipws set to true ). Then (if good ), it extracts characters from its associated stream buffer object as if calling its member functions sbumpc or sgetc , and finally destroys the sentry object before returning.

The number of characters successfully read and stored by this function can be accessed by calling member gcount .

Parameters

Return Value

The first signature returns the character read, or the end-of-file value ( EOF ) if no characters are available in the stream (note that in this case, the failbit flag is also set).

All other signatures always return *this . Note that this return value can be checked for the state of the stream (see casting a stream to bool for more info).

Errors are signaled by modifying the internal state flags:

flag error
eofbit The function stopped extracting characters because the input sequence has no more characters available (end-of-file reached).
failbit Either no characters were written or an empty c-string was stored in s .
badbit Error on stream (such as when this function catches an exception thrown by an internal operation).
When set, the integrity of the stream may have been affected.

Multiple flags may be set by a single operation.

If the operation sets an internal state flag that was registered with member exceptions , the function throws an exception of member type failure .

Функция cin.get()

Объясните пожалуйста мне функцию cin.get() . Прочитал про него в Дейтел, но там как то не очень подробно и хорошо она описана. Может кто-то мне поподробнее рассказать, если не трудно?

Denis's user avatar

Когда метод get() вызывается с аргументом типа char или вообще аргументов, он извлекает следующий символ ввода, даже если это пробел, знак табуляции или символ новой строки. Версия get(char& ch) присваивает входящий символ своему аргументу, а версия get(void) просто использует входной символ, преобразует его в целочисленный тип (обычно — int) и возвращает это значение.

Плюс пару слов об еще парочке перегруженных разновидностях:

Первая форма функции get() считывает символы в массив, на который ссылается указатель buf , пока не будет считан num — 1 символов, обнаружен символ перехода на следующую строку или достигнут конец файла. Эта функция записывает нулевой символ в конец массива, на который ссылается указатель buf . Символ перехода на новую строку не считывается (!). Он остается в потоке, пока не будет выполнена следующая операция ввода.

Вторая форма функции get () считывает символы в массив, на который ссылается указатель buf , пока не будет считан num — 1 символов, обнаружен символ delim или достигнут конец файла. Функция записывает нулевой символ в конец массива, на который ссылается указатель buf . Символ delim не считывается (!). Он остается в потоке, пока не будет выполнена следующая операция ввода.

 

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *