📅  最后修改于: 2023-12-03 15:14:09.269000             🧑  作者: Mango
cin.peek()
is a C++ input stream function that returns the next character in the input stream without reading it. It is used to check the next input character before reading it, and the input stream remains unchanged.
The syntax for cin.peek()
is as follows:
int cin.peek();
cin.peek()
returns the next character in the input stream as an integer. It returns -1 if there are no more characters present in the input stream.
#include <iostream>
using namespace std;
int main()
{
char c;
cout << "Enter a character: ";
// peek the next character
int ch = cin.peek();
// check if next character is a newline
if (ch == '\n')
{
cout << "You entered a newline character!" << endl;
}
else
{
cin >> c;
cout << "You entered the character: " << c << endl;
}
return 0;
}
In the above example, we first peek at the next character in the input stream using cin.peek()
. We then check if the next character is a newline character. If it is, we print a message saying so. Otherwise, we read in the character using cin >> c
and print it.
In conclusion, cin.peek()
is a useful C++ input stream function that allows us to check the next character in the input stream without reading it. It is commonly used to conditionalise the program flow based on the next input character.