第06章 分支语句和逻辑运算符

本章内容包括:

  • if语句
  • if else语句
  • 逻辑运算符:&&,||和!
  • cctype字符函数库
  • 条件运算符:?:
  • switch语句.
  • continue和break语句
  • 读取数字和循环
  • 基本文件输入/输出

设计智能程序的一个关键是使程序具有决策能力.

6.1 if语句

  • 程序清单6.1 if.cpp

6.1.1 if else语句

  • 程序清单6.2 ifelse.cpp

6.1.2 格式化if else语句

  • 由于C++是自由格式语言,因此只要使用大括号将语句括起,对大括号的位置没有任何限制.

6.1.3 if else if else结构

  • 程序清单6.3 ifelseif.cpp

6.2 逻辑表达式 
6.2.1 逻辑OR运算符:||

  • 程序清单6.4 or.cpp

6.2.2 逻辑AND运算符:&&

  • 程序清单6.5 and.cpp

6.2.3 用&&来设置取值范围

  • 程序清单6.6 more_and.cpp

6.2.4 逻辑NOT运算符:!

  • 程序清单6.7 not.cpp

6.2.5 逻辑运算符细节 
6.2.6 其他表示方式 
6.3 字符函数库cctype

程序清单6.8 cctypes.cpp
// cctypes.cpp -- using the ctype.h library
#include <iostream>
#include <cctype>              // prototypes for character functions
int main()
{
    using namespace std;
    cout << "Enter text for analysis, and type @"
            " to terminate input.\n";
    char ch;  
    int whitespace = 0;
    int digits = 0;
    int chars = 0;
    int punct = 0;
    int others = 0;
    cin.get(ch);                // get first character
    while (ch != '@')            // test for sentinel
    {
        if(isalpha(ch))         // is it an alphabetic character?
            chars++;
        else if(isspace(ch))    // is it a whitespace character?
            whitespace++;
        else if(isdigit(ch))    // is it a digit?
            digits++;
        else if(ispunct(ch))    // is it punctuation?
            punct++;
        else
            others++;
        cin.get(ch);            // get next character
    }
    cout << chars << " letters, "
         << whitespace << " whitespace, "
         << digits << " digits, "
         << punct << " punctuations, "
         << others << " others.\n";
    // cin.get();
    // cin.get();
    return 0; 
}

6.4 ?:运算符

  • 条件运算符(?:),它是C++中唯一一个需要3个操作数的运算符.
expression1?expression2:expression3;
  • 1
  • 程序清单6.9 condit.cpp

6.5 switch语句

  • 程序清单6.10 switch.cpp

6.5.1 将枚举量用作标签

  • 程序清单6.11 enum.cpp

6.5.2 switch和if else

  • switch并不是为处理取值范围而设计的.

6.6 break和continue语句

  • continue语句用于循环中,让程序跳过循环体中余下的代码,并开始新一轮循环.
  • 程序清单6.12 jump.cpp
  • 和C语言一样,C++也有goto语句.

6.7 读取数字的循环

  • 程序清单6.13 cinfish.cpp
  • 程序清单6.14 cingolf.cpp

6.8 简单文件输入/输出 
6.8.1 文本I/O和文本文件 
6.8.2 写入到文本文件中

  • 使用文件输出的主要步骤如下: 
    1. 包含头文件fstream.
    2. 创建一个ofstream对象.
    3. 将该ofstream对象同一个文件关联起来.
    4. 就像使用cout那样使用该ofstream对象.
程序清单6.15 outfile.cpp
// outfile.cpp -- writing to a file
#include <iostream>
#include <fstream>                  // for file I/O
int main()
{
    using namespace std;
    char automobile[50];
    int year;
    double a_price;
    double d_price;
    ofstream outFile;               // create object for output
    outFile.open("carinfo.txt");    // associate with a file
    cout << "Enter the make and model of automobile: ";
    cin.getline(automobile, 50);
    cout << "Enter the model year: ";
    cin >> year;
    cout << "Enter the original asking price: ";
    cin >> a_price;
    d_price = 0.913 * a_price;
// display information on screen with cout
    cout << fixed;
    cout.precision(2);
    cout.setf(ios_base::showpoint);
    cout << "Make and model: " << automobile << endl;
    cout << "Year: " << year << endl;
    cout << "Was asking $" << a_price << endl;
    cout << "Now asking $" << d_price << endl;
// now do exact same things using outFile instead of cout
    outFile << fixed;
    outFile.precision(2);
    outFile.setf(ios_base::showpoint);
    outFile << "Make and model: " << automobile << endl;
    outFile << "Year: " << year << endl;
    outFile << "Was asking $" << a_price << endl;
    outFile << "Now asking $" << d_price << endl;

    outFile.close();                // done with file
    // cin.get();
    // cin.get();
    return 0;
}
  • 注意:方法close()不需要使用文件名作为参数,这是因为outFile已经同特定的文件关联起来.如果您忘记关闭文件,程序正常终止时将自动关闭它.
  • 警告:打开已有的文件,以接受输出时,默认将它其长度截短为零,因此原来的内容将丢失.

6.8.3 读取文本文件

  • 重要的是,声明一个ifstream对象并将其同文件关联起来后,便可以想使用cin那样使用它.
  • 程序清单6.16 sumafile.cpp
// sumafile.cpp -- functions with an array argument
#include <iostream>
#include <fstream>          // file I/O support
#include <cstdlib>          // support for exit()
const int SIZE = 60;
int main()
{
    using namespace std;
    char filename[SIZE];
    ifstream inFile;        // object for handling file input
    cout << "Enter name of data file: ";
    cin.getline(filename, SIZE);
    inFile.open(filename);  // associate inFile with a file
    if (!inFile.is_open())  // failed to open file
    {
        cout << "Could not open the file " << filename << endl;
        cout << "Program terminating.\n";
        // cin.get();    // keep window open
        exit(EXIT_FAILURE);
    }
    double value;
    double sum = 0.0;
    int count = 0;          // number of items read
    inFile >> value;        // get first value
    while (inFile.good())   // while input good and not at EOF
    {
        ++count;            // one more item read
        sum += value;       // calculate running total
        inFile >> value;    // get next value
    }
    if (inFile.eof())
        cout << "End of file reached.\n";
    else if (inFile.fail())
        cout << "Input terminated by data mismatch.\n";
    else
        cout << "Input terminated for unknown reason.\n";
    if (count == 0)
        cout << "No data processed.\n";
    else
    {
        cout << "Items read: " << count << endl;
        cout << "Sum: " << sum << endl;
        cout << "Average: " << sum / count << endl;
    }
    inFile.close();         // finished with the file
    // cin.get();
    return 0;
}
  • 警告:Windows文本文件的每行都以回车字符和换行符结尾;通常情况下,C++在读取文件时将这两个字符转换为换行符,并在写入文件时执行相反的转换.有些文本编辑器(如Metrowerks CodeWarrior IDE编译器),不会自动在最后一行末尾加上换行符.因此,如果读者使用的是这种编辑器,请在输入最后的文本按下回车键,然后再保存文件.

6.9 总结 
6.10 复习题 
6.11 编程练习

附件:本章源代码下载地址

猜你喜欢

转载自blog.csdn.net/weixin_39345003/article/details/82110258