C++ istream::get() function
The C++ std::istream::get() function is used to read characters from an input stream. It can operate in several modes: reading a single character, reaading character into a buffer until a specified delimiter is encountered, or reading characters into buffer of a specified size.
This function does not skip the whitespace by default, making it distinct from functions like operator>>.
Syntax
Following is the syntax for std::istream::get() function.
int get();istream& get (char& c); or istream& get (char* s, streamsize n);istream& get (char* s, streamsize n, char delim); or istream& get (streambuf& sb);istream& get (streambuf& sb, char delim);
Parameters
- c − It indicates the reference to a character where the extracted value is stored.
- s − It indicaets the pointer to an array of characters where extracted characters are stored as a c-string.
- n − It indicates the maximum number of characters to write to s (including the terminating null character).
- delim − It indicates the explicit delimiting character.
- sb − It indicates a basic_streambuf object on whose controlled output sequence the characters are copied.
Return Value
This function returns the character read, or the end-of-file value (traits_type::eof()) if no characters are available in the stream (note that in this case, the failbit flag is also set).
Exceptions
If an exception is thrown, the object is in a valid state.
Data races
Modifies c, sb or the elements in the array pointed by s and modifies the stream object.
Example
In the following example, we are going to read the single character.
#include <iostream>
int main()
{
char x;
std::cout << "Enter A Character : ";
std::cin.get(x);
std::cout << "Entered Character : " << x << std::endl;
return 0;
}
Output
Output of the above code is as follows −
Enter A Character : B Entered Character : B
Example
Consider the following example, where we are going to use the get() to read characters from input stream until a delimiter is encounterd.
#include <iostream>
int main()
{
char a[10];
std::cout << "Enter Input : ";
std::cin.get(a, 10, ',');
std::cout << "Entered Input : " << a << std::endl;
return 0;
}
Output
Following is the output of the above code −
Enter Input : Hello, Namaste! Entered Input : Hello