6. 分支和逻辑运算符

84 阅读3分钟

6. 分支和逻辑运算符


if、else

if(test-expr)
    body;
else if(test-expr)
    body;
else
    body;
​

逻辑运算符&&、||、!,三目运算符?:

&&、||

&& 和 || 都是顺序点,即从左往右执行。 &&优先级高于||

有两个规定:

  • 当左侧满足要求时,将不会执行右侧表达式
  • 左侧表达式会在右侧执行之前产生全部副作用
// || 或, 一真则真
i++ < 6 || i == j;  // 在执行i == j 之前,i的值将为11. 如果i++ < 6 为true, 则不会进行 i==j判定
// && 与,一假则假
5 == 6 && 4 == 4;  // 先执行5 == 6,为假,则不会执行4 == 4

!

!将它后面的表达式取反。所以当!用在while、if时,不要想着将!与while、if结合。直接计算后面的表达式就行,将后面表达式的值取反,再看真假,真则执行,假则不执行

  • !0 为真

  • !的优先级高于所有关系运算符和算术运算符

    • !(x > 5) 等价于 x <=5
    • !x > 5 等价于 !x 大于5

? :

// expr1为真吗? 为真则表达式的值为expr2,为假表达式值则为expr3
expr1 ? expr2 :expr3;  
​
// 将表达式值赋给c
c = expr1 ? expr2 :expr3; 

switch

// 使用整型表达式的值来选择情况执行
// char 也是整型哦
// 也可以用枚举,枚举量也是整型哦
// 每个情况后面必须使用break语句,否则将会向下执行。
switch(整形表达式)  
{
    case label1 : {...; break;};
    case label2 : {...; break;};
        ...
    default : {...; break;};
        
}

break、continue

break; :打破循环。跳到循环后面执行。

continue;:跳过循环体中剩下的代码,使进入下一次循环。

读取数字循环

// 如果要读取一些数字,并把它们放到数组内。
const int kMax = 5;
​
int golf[kMax];
​
for (int i =0; i < kMax; i++)
{
    cout << "round #" << i+1 << ": ";
    // cin >> golf[i] 未发生错误则次表达式为true,!完则为false。跳过循环体。
    // 如果发生错误则进入循环体,进行清理
    while(!(cin >> golf[i]))  // (cin >> golf[i]) == false
    {
        cin.clear;  // 清理错误位
        while(cin.get() != '\n')  // 清理输入队列
            continue;
        cout << "Please enter a number: ";
    }
}

文件IO

// 文件output  写文件#include <fstream>  // 1.包含文件IOusing namespace std;
​
int main()
{
    ofstream fout;  // 2.创建文件输出对象
    fout.open("carinfo.txt");  // 3.将oftream对象与一个文件关联起来
    fout << "Now asking $" << d_price << endl;  // 4.像操作cout那样操作文件。
    
    
    fout.close;  // 5.关闭文件
}
// 文件input  读文件#include <fstream>  // 1. 包含文件IO
#include <iostream>
​
using namespace std;  
​
int main()
{
    filename = "carinfo.txt"
    ifstream fin;  // 2.创建读文件对象
    fin.open(filename);  // 3.绑定文件
    
    if(!fin.is_open())  // 4.处理文件未被正常打开
    {
        cout << "Could not open the file "  << filename << endl;
        cout << "Program terminating! \n";
        exit(EXIT_FAILURE);
    }
    
    double value;
    
    fin >> value;
    
    while(fin.good())  // 5.1. 读取正常打开则进行操作  .good()方法指出最后一次读取输入的操作是否成功
    {
        fin >> value;  // 和cin >> 一样使用
    }
    
    if(fin.eof())  // 5.2. 正常到文件尾
    {
        cout << "End of file reached.\n";
    }
    else if(fin.fail())  // 5.3. 文件内数据格式错误
    {
        cout << "输入终止,数据不匹配"  << endl;
    }
    else  // 5.4. 其他错误
    {
        cout << "读取终止,因为未知原因。"  << endl;
    }
    
    fin.close();  // 6. 关闭文件
}