Basic istream peak() method in C++
In this article, we will discuss the Basic_istream::peak() method in C++ with its syntax, example.
What is the Basic_istream::peak() method?
The basic_istream::peek() method is a member function of the basic_istream class in the C++ Standard Template Library (STL) for input streams, which empowers us to examine the next character in the input stream without actually removing it. This control over the stream allows us to make informed decisions on how to process the input based on the upcoming character.
Syntax:
It has the following syntax:
int peek();
Return Value:
It returns the value of the next character in the stream as an int_type (usually an int) or EOF (end-of-file) if there are no more characters to read or an error has occurred.
Key Points of the Basic_istream::peak() Method:
Several key points of the basic_istream::peak() method are as follows:
- Non-destructive: Unlike get(), the basic_istream::peek() doesn't remove the character from the stream. Subsequent reads or extractions will still encounter the same character.
- Error Handling: The basic_istream::peek() method is designed to set the stream's error state flags if an error occurs during the peek operation, ensuring a reliable error handling mechanism.
- Exception Throwing: When encountering errors, behaviour depends on the stream's exception handling settings. We may need to check the stream's state before making assumptions about the returned value.
Example:
Let us take an example to illustrate the basic_istream::peak() in C++.
#include <iostream>
#include <string>
#include <cctype>
int main () {
std::cout << "Hey, enter a number or a word: ";
std::cout.flush();
std::cin >> std::ws;
int c = std::cin.peek();
if ( c == EOF ) return 1;
if ( std::isdigit(c) )
{
int num;
std::cin >> num;
std::cout << "your number: " << num << '\n';
}
else
{
std::string wrd;
std::cin >> wrd;
std::cout << "Your word: " << wrd << '\n';
}
return 0;
}
Output:
![Basic_istream::peak() method in C++](https://static.tutorialandexample.com/cpp/basic-istream-peak-method-in-cpp1.png)
Data races.
- The stream object is altered.
- Excluding the standard stream object (cin) while it is in stdio synchronization. Data races might occur from concurrent access to the same stream object. No data races are initiated in this case. Regarding the order in which read characters are allocated to threads, there are no guarantees.
Conclusion:
In conclusion, the basic_istream::peek() method in C++ is a powerful tool that allows us to inspect the next character in an input stream without consuming it. It can be particularly useful in scenarios where we need to perform conditional parsing or lookahead operations, enhancing the efficiency and flexibility of the code.