【c++primerplus】【循环和关系表达式】

(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"
};

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值