2

I read a c++ book and it shows this code,

#include <iostream>
int main()
{   
    int total, choice;
    std::cin >> total >> choice;
    if (!std::cin) //bad input
    {
        std::cout <<total << choice;
    }
}

Actually, I don't know what is good input and bad input because no matter what I input, it still cannot cout, so how to output a 'good' input?

4daJKong
  • 1,825
  • 9
  • 21
  • The code does not have the good path. `if (!cin)` means something went wrong with parsing the input to the 2 integers. So, if you enter `15 abc` it should print `15 `. https://godbolt.org/z/Kj3TKPzPn – mch Jun 24 '22 at 09:28
  • Have you tried inputting text, not numbers? – Caleth Jun 24 '22 at 09:30

1 Answers1

2

!cin checks is fail() returns true for the stream. Before c++11 this was going through void*, after that it is using bool operator as indicated here. What fail checks is if failbit or badbit are up for the stream and you can read more about them here.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176