c++入门之 深入cin

cin 表示输入流,但是究其本质,又能认识到什么呢?先上代码:

 1 #include "iostream"
 2 const int MAX{5};//c++11中使用{}进行重新命名
 3 int main()
 4 {
 5     using namespace std;
 6     double fish[MAX];
 7     //////////
 8     bool sym;
 9     int test;
10     sym = bool(cin >> test);
11     cout << sym << endl;//这里是用来测试cin输入如果输入的不是对应的类型,那么将返回什么.
12     /////////
13     cout << "please enter the weights of dish.\n";
14     cout << "you may enter up to" << MAX << " fish<q to terminate>.\n";
15     cout << "fish #1: ";
16     int i{0};
17     while (i < MAX && cin >> fish[i]){//注意两点:数组是从[0]元素开始的!!这里输入了double型数据判定为true。
18         if (++i < MAX)                 //输入了其他的字母判定为false。因此若输入了字母则会结束
19             cout << i << endl;
20             cout << "fish #" << i + 1 << ":";
21     }
22         double total{ 0.0 };
23         for (int j{ 0 }; j < i; j++)
24             total = total + fish[j];
25         if (i == 0)
26             cout << "No fish\n";
27         else
28             cout << total / i << "=ave weight of " << i << "fish\n";
29         cout << "Done.\n";
30         system("pause");
31         return 0;
32         
33 }

上述中8-11行的代码,我们验证了对于int sym, cin>>sym的返回值,我们通过打印一个布尔变量的值来验证。对于输入的如 1,3.14返回1,对于'w',"wr"返回0.

下面一段文字是对cin这种操作的详尽解读.

而第17行的while()中的判定条件则十分明确的表明了:可以将通过cin>>test的返回值来判定循环是否终止.

在后续学习中,应当逐渐深入cin>>test的意义.

猜你喜欢

转载自www.cnblogs.com/shaonianpi/p/9764529.html