C++ Primer Plus学习笔记05-循环和关系表达式

1 for循环

// introducing the for loop
#include <iostream>
int main()
{
  using namespace std;
  int i; // create a counter
  // initialize; test; update
  for (i = 0; i < 5; i++)
    cout << "C++ knows loops.\n";
  cout << "C++ knows when to stop." << endl;
  return 0;
}

C++不限制test-expression的值,它将结果强制转换为bool类型。

for循环是入口条件(entry-condition)循环——每轮循环之前都将计算测试表达式的值。更新表达式(update-expression)在每轮循环结束时执行,此时循环体已经执行完毕。

递增运算符++和递减运算符--

前缀版本位于操作数前;后缀版本位于操作数后。前缀表达式值为操作数加/减1,后缀表达式值为操作数。

前缀和后缀格式的执行速度在类上有差别。前缀函数:值加1返回结果;后缀函数:复制一个副本,加一,返回副本。因此,前缀版本比后缀版本效率高。

2 while循环

while(name[i] != '\0')
{
  cout << name[i] << ": " << int(name[i]) << endl;
  i++;
}

C++建立类型别名的方式:

  1. 使用预处理器
  2. 使用typeof关键字
#define BYTE char // preprocessor replaces BYTE with char

typedef char byte; // make byte an alias for char
// typedef不会创建新类型,只是为已有的类型建立一个新名称。

3 do while循环

do
{
  cin >> n;
} while (n != 7);

4 基于范围的for循环(C++11)

对数组(或容器类)的每个元素执行相同的操作

double prices[5] = {4.9, 10.9, 6.78, 7.9, 8.4};
for (double x : prices)
  cout << x << std::endl;

// 修改数组元素
for (double &x : prices) // &表明x是一个引用变量
  x = x * 0.8 

循环和文本输入

// reading chars with a while loop
#include <iostream>
int main()
{
  using namespace std;
  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在读取基本类型时,将忽略空格和换行符。另外,发送给cin的输入被缓冲,即只有在用户按下回车键后输入的内容才会被发送给程序。

// using cin.get(char)
#include <iostream>
int main()
{
  using namespace std;
  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;
}

包括空格在内的字符都被接收,但是输入仍然被缓冲。

如果输入来自于文件,可以检测文件尾(EOF)来判断输入是否结束。C++输入工具和操作系统协同工作来检测文件尾并将这种信息告知程序。
检测到EOF后,cin将两位(eofbitfailbit)都设置为1。设置后,cin将不读取输入。如果稍后要读取其他输入,cin.clear()方法可能清除EOF标记使输入继续进行。

// reading chars to end of file
#include <iostream>
int main()
{
  using namespace std;
  char ch;
  int count = 0;
  cin.get(ch);
  while(cin.fail() == false) // test for EOF
  {
    cout << ch;
    ++count;
    cin.get(ch);
  }
  cout << endl << count << " characters read\n";
  return 0;
}

istream类提供了一个可以将istream对象(如cin)转换为bool值的函数。当该对象出现在需要`bool=值的地方,该转换函数将被调用。

while(cin.get(ch))
{
  cout << ch;
  ++count;
}

6 嵌套循环和二维数组

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值