gpt4 book ai didi

c++ - cin.peek() 在 C++ 中如何工作?

转载 作者:行者123 更新时间:2023-11-28 01:48:18 25 4
gpt4 key购买 nike

当我将 cin.peek() 与“char”数据类型一起使用时,它工作得很好,但它不适用于“string”数据类型。这很好用:

#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;
}

如果输入是“dce”它打印“ha”但是 下面的代码不做同样的工作:

#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;
}

是不是字符串数据类型更合适,因为我们将单词存储在“a”变量中。 “char”数据类型可以用来存储单词还是只能存储单个字母?

最佳答案

cin.peek()
返回输入序列中的下一个字符,而不提取它:该字符保留为要从流中提取的下一个字符。

对于你的两个代码,输入是 dce

在第一个代码中

char a;
cin>>a

它只从输入缓冲区中获取 dce 仍在其中,因此当您执行 cin.peek() 时,它会得到缓冲区中的下一个字符是 c。但是对于第二个代码

string a;
cin>>a;

由于数据类型是字符串,它从输入流缓冲区中获取整个 dce,当您执行 cin.peek() 时,它会检查流中是否有任何内容但现在没有了。因此它返回 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:

关于c++ - cin.peek() 在 C++ 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43993795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com