Reputation: 2572
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';
}
And many C++ websites and forums using such a thing:
while(std::cin.peek() != '\n)
; do somthing
But after reading the note on C++ primer I am confused. It is said that those functions get(), peek()
return an int
not a char
so we mustn't assign the result into a char but into an int
.
It is said there that Characters are converted first to unsigned char
then promoted to int
.
So how could I uses these functions correctly?
Upvotes: 1
Views: 761
Reputation: 29
so we mustn't assign the result into a char but into an int
while(std::cin.peek() != '\n')
is not assigning the result of peek()
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/
Upvotes: 1