Условие if (!cin)

Что означает это условие, не понимаю как оно работает.

int a = 0;
	cin >> a;
	if (!cin)
		cout << "Hi";
	if (cin)
		cout << "m";

Вот отрывок. Почему условие связано с предыдущей инструкцией (cin>>a), если оно от условия ограждено. Не понимаю смысл этой конструкции

Ну, надо посмотреть, что такое cin. Возможно это переменная. Тогда у неё есть тип (узнать его название, возможно это std::istream или что-то вроде того). В этом типе надо поискать операцию приведения к булевскому типу и почитать её код.

Чтобы понять, почему к булевскому, надо почитать текст стандарта используемой версии языка, раздел про оператор if. Стандарт C++ ISO/IEC 14882, раздел 6.4 “оператор выбора” (Selection statements) и 6.4.1 про if ( ̶6̶.̶4̶.̶2̶ ̶-̶ ̶э̶т̶о̶ ̶д̶р̶у̶г̶о̶й̶,̶ ̶п̶р̶о̶ ̶s̶w̶i̶t̶c̶h̶)

6.4
§4 The value of a condition that is an initialized declaration in a statement other than a switch statement is the value of the declared variable contextually converted to bool (Clause 4). If that conversion is ill-formed, the program is ill-formed. The value of a condition that is an initialized declaration in a switch statement is the value of the declared variable if it has integral or enumeration type, or of that variable implicitly converted to integral or enumeration type otherwise. The value of a condition that is an expression is the value of the expression, contextually converted to bool for statements other than switch; if that conversion is ill-formed, the program is ill-formed. The value of the condition will be referred to as simply “the condition” where the usage is unambiguous.

6.4.1 The if statement [stmt.if]
1 If the condition (6.4) yields true the first substatement is executed. If the else part of the selection statement is present and the condition yields false, the second substatement is executed. If the first substatement is reached via a label, the condition is not evaluated and the second substatement is not executed. In the second form of if statement (the one including else), if the first substatement is also an if statement then that inner if statement shall contain an else part.

Оператор bool возвращает true, если поток не содержит ошибок и готов к операциям ввода/вывода. Он эквивалентен вызову функции-члена fail() с отрицанием (!fail()).
Таким образом, при использовании объекта std::istream в условном выражении, например, в операторе if, будет вызван оператор bool, который проверит, что поток не содержит ошибок и может выполнять операции ввода/вывода.

Всё это изучать надо самостоятельно. Сейчас это крайне просто делать с поисковиками типа phind.com. Тексты стандартов выкачать и сложить себе в электронную библиотеку, для этого использовать программу Calibre. Да, надо поработать. Но тут получается, что я-то поработал и нашел это всё. А надо тебе самому.

1 лайк

Ого, спасибо больше за подробный ответ! :+1: Я просто только начал изучать и поэтому не знаю ещё где что какую информацию брать, по книжке Страуструпа изучаю сейчас