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

650 Views Asked by At

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?

1

There are 1 best solutions below

5
user1819102 On

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/