PAT 甲级1008 Elevator
// 1008 Elevator.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
int main()
{
int sum = 0, a, now = 0, n;
cin >> n;
while (n-- > 0) {
cin >> a;
if (a > now) {
sum += (a - now) * 6;
}
else {
sum += (now - a) * 4;
}
now = a;
sum += 5;
}
cout << sum;
return 0;
}
用cin >> a作为循环:
int a;
while(cin >> a) {
code
}
该方法检测流的状态来判断结束,如果流有效(没有遇到错误),检测成功
如果遇到文件结束符,或遇到一个无效输入,如输入的不是一个整数,条件就为假
参考在while中使用cin>>a 为条件,注意事项_欢迎来到小丁的技术空间-优快云博客
#include <iostream>
using namespace std;
int main() {
int a;
while (cin >> a) {
cout << a << endl;
}
char c = 'e';
cin >> c;
cout << c << endl;
return 0;
}
在这个代码中,输入12a,输出为:
1
2
e
当输入a时,因为不满足整型跳出循环,此时没有进入cin >> c,而是直接输出c的值为’e’。
为什么没有进入cin呢?问题出在输入流cin,它是一个输入流对象,当进行while循环时我们输入一个字母a来结束该循环,此时输入流的状态为false,所以运行到cin >> c时,因为cin的状态为false,所以跳过了。要加入cin.clear()清除错误状态。
#include <iostream>
using namespace std;
int main() {
int a;
while (cin >> a) {
cout << a << endl;
}
cin.clear();
char c = 'e';
cin >> c;
cout << c << endl;
return 0;
}
此时输出为
1
2
a
在循环的最后因为输入流状态为false,导致a还在缓冲区中未读取,运行到cin >> c时,将c赋值为a,输出a
在这个循环中,我们输入字母可能只是为了结束这个循环,而不想对该字母做出任何处理,需要使用cin.ignore()。
#include <iostream>
using namespace std;
int main() {
int a;
while (cin >> a) {
cout << a << endl;
}
cin.clear();
cin.ignore();
char c = 'e';
cin >> c;
cout << c << endl;
return 0;
}
//输入: 1 2 a d
//输出: 1 2 d
cin.ignore()的一个常用功能就是用来清除以回车结束的输入缓冲区的内容,消除上一次输入对下一次输入的影响。
如果不给参数如此例,默认参数为cin.ignore(1, EOF),即把EOF前的1个字符清掉,没有遇到EOF就清掉一个字符然后结束。
字母a被消除了,缓冲区为空所以等待用户输入,输入d后输出