如何正确使用std :: cin.get()和std :: cin.peek()的返回值? [英] How to use correctly the return value from std::cin.get() and std::cin.peek()?
问题描述
我一直以这种方式使用 peek(),get()
:
I've been always using peek(), get()
this way:
int main(){
std::string str;
int value{};
if(std::isdigit(std::cin.peek()))
std::cin >> value;
else
std::getline(cin, str);
std::cout << "value : " << value << '\n';
std::cout << "str: " << str << '\n';
}
许多C ++网站和论坛都使用这样的东西:
And many C++ websites and forums using such a thing:
while(std::cin.peek() != '\n)
; do somthing
-
但是在阅读了有关C ++入门的注释后,我感到困惑.据说这些函数
get(),peek()
返回的是int
而不是char
,因此我们不能将结果分配给字符,但变成int
.But after reading the note on C++ primer I am confused. It is said that those functions
get(), peek()
return anint
not achar
so we mustn't assign the result into a char but into anint
.据说那里的字符首先被转换为
unsigned char
,然后被提升为int
.It is said there that Characters are converted first to
unsigned char
then promoted toint
.那我该如何正确使用这些功能?
So how could I uses these functions correctly?
推荐答案
所以我们不能将结果分配给char而是分配给int
so we mustn't assign the result into a char but into an int
while(std :: cin.peek()!='\ n')
未将peek()
的结果分配给char.它正在比较一个char和一个int.在这里,char被隐式转换为int,然后进行比较.多亏@MM,以这种方式使用它更安全:while(std :: cin.good()&& std :: cin.peek()!='\ n')
while(std::cin.peek() != '\n')
is not assigning the result ofpeek()
to a char. It is comparing a char and an int. Here the char is implicitly converted to an int and then compared. Thanks to @M.M, it is safer to use it this way:while(std::cin.good() && std::cin.peek() != '\n')
https://www.learncpp.com/cpp-tutorial/implicit-type-conversion-coercion/
这篇关于如何正确使用std :: cin.get()和std :: cin.peek()的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!