Maestro
Maestro

Reputation: 2572

How to use correctly the return value from std::cin.get() and std::cin.peek()?

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

So how could I uses these functions correctly?

Upvotes: 1

Views: 761

Answers (1)

user1819102
user1819102

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

Related Questions