简体   繁体   中英

How does cin.peek() work in c++?

when i use cin.peek() with a "char" data type it works perfectly fine but it does not work with "string" data type. this works fine:

#include<iostream>
using namespace std;
int main(){
  cout<<"enter a word"<<endl;
  char a;
  cin>>a;
if(cin.peek()=='c'){
  cout<<"ha"<<endl;
}
return 0;
}

if input is "dce" it prints "ha" but the code below doesnot do the same job:

#include<iostream>
#include<string>
using namespace std;
int main(){
  cout<<"enter a word"<<endl;
  string a;
  cin>>a;
if(cin.peek()=='c'){
  cout<<"ha"<<endl;
}
return 0;
}

isn't the string data type more appropriate as we are storing words in "a" variable. can "char" data type be used to store words or only single letters?

cin.peek()
Returns the next character in the input sequence, without extracting it: The character is left as the next character to be extracted from the stream.

For your both codes the input is dce

In first code

char a;
cin>>a

It take only d from the input buffer and ce is still in it, So when you do cin.peek() it gets the next character from buffer that is c . But for second code

string a;
cin>>a;

As the data-type is string it takes whole dce from input stream buffer and when you do cin.peek() it checks if there is anything in the stream but now there isn't. Hence it returns EOF

If there are no more characters to read in the input sequence, or if any internal state flags is set, the function returns the end-of-file value (EOF), and leaves the proper internal state flags set:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM