(c++11)基于范围的for循环:这简化了一种常见的循环任务:对数组(或容器类,如vector和array)的每个元素执行相同的操作。
double prices[5] = {4.99, 10.99, 6.87, 7.99, 8.49}
for(double x : prices)
cout << x << std::endl;
for(double &x : prices)
x = x * 0.8;
for(int x : {3, 5, 2, 8, 6})
cout << x << " ";
int main() {
char ch;
int count = 0;
cout << "Enter characters; enter # to quit:\n";
cin >> ch;
while (ch != '#') {
cout << ch;
++count;
cin >> ch;
}
cout << endl << count << " characters read\n";
return 0;
}
cin在读取char值时,与读取其他基本类型一样,cin将忽略空格和换行符。因此输入中的空格没有被回显,也没有被包括在计数内。更复杂的是,发送给cin的输入被缓冲。这意味着只有用户按下回车键后,他输入的内容才会发送给程序。
使用cin.get(ch)替换。
int main() {
char ch;
int count = 0;
cout << "Enter characters; enter # to quit:\n";
cin.get(ch);
while (ch != '#') {
cout << ch;
++count;
cin.get(ch);
}
cout << endl << count << " characters read\n";
return 0;
}
很多操作系统都允许通过键盘来模拟文件尾条件(windows是Ctrl+Z 和 Enter)。检测到EOF后,cin将两位(eofbit 和 failbit)都设置为1,可以通过成员函数eof()来查看eofbit是否被设置;如果检测到EOF,则cin.eof()将返回bool值true。failbit 对应 成员函数 fail()。注意,这两个方法报告最近的读取结果;也就是说他们是事后报告而不是预先报告。
int main() {
char ch;
int count = 0;
cout << "Enter characters; enter # to quit:\n";
cin.get(ch);
while (cin.fail() == false) {
cout << ch;
++count;
cin.get(ch);
}
cout << endl << count << " characters read\n";
return 0;
}
方法cin.get(char)的返回值是一个cin对象。然而,istream类提供了一个可以将istream对象(如 cin)转换为bool值的函数;当cin出现在需要bool值的地方(如在while循环的测试条件中)时,该转换函数将被调用。
while(cin.get(char)){
;\\
}
三种“二维数组”方式
const char *cities[5] = {
"baoding",
"zhengzhou",
"shijiazhuang"
};
char cities[5][25] = {
"baoding",
"zhengzhou",
"shijiazhuang"
};
const string cities[5] = {
"baoding",
"zhengzhou",
"shijiazhuang"
};