問題描述
整個夏天我一直在使用Accelerated C++"來學(xué)習(xí) C++,但有一個我似乎不太理解的概念.
I have been using "Accelerated C++" to learn C++ over the summer, and there's a concept which I don't seem to understand properly.
為什么
int x;
if (cin >> x){}
相當(dāng)于
cin >> x;
if (cin){}
通過查看代碼,在我看來,我們正在使用 cin 作為變量.但是,我認(rèn)為這是一個函數(shù).當(dāng) x 具有我們在鍵盤中輸入的任何值時,為什么我們可以這樣使用 cin?
By looking at the code, it seems to me that we're using cin as a variable. But, I thought it was a function. Why can we use cin in this way when it is x that has whatever value we input into our keyboard?
推薦答案
cin
是 istream
表示標(biāo)準(zhǔn)輸入流.它對應(yīng)于cstdio
流stdin
.操作符 >>>
重載流返回對同一流的引用.流本身可以通過轉(zhuǎn)換運算符在布爾條件中評估為真或假.
cin
is an object of class istream
that represents the standard input stream. It corresponds to the cstdio
stream stdin
. The operator >>
overload for streams return a reference to the same stream. The stream itself can be evaluated in a boolean condition to true or false through a conversion operator.
cin
提供格式化的流提取.操作cin>>x;
cin
provides formatted stream extraction. The operation
cin >> x;
如果一個非數(shù)字值是一個整數(shù),那么x"是一個整數(shù)將會失敗進入.所以:
where "x" is an int will fail if a non-numeric value is entered. So:
if(cin>>x)
如果您輸入的是字母而不是數(shù)字,將返回 false
.
will return false
if you enter a letter rather than a digit.
這個關(guān)于使用 C++ I/O 的技巧和竅門 的網(wǎng)站也會對您有所幫助.
This website on tips and tricks using C++ I/O will help you too.
這篇關(guān)于if (cin >> x) - 為什么你可以使用那個條件?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!