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 anintnot acharso we mustn't assign the result into a char but into anint.It is said there that Characters are converted first to
unsigned charthen promoted toint.
So how could I uses these functions correctly?
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/