Chapter Review

1

Both version give the same answers, but the if else version is more efficient. Consider what happens, for example, when ch is a space. Version 1, after incrementing spaces, tests whether the character is a newline. This wastes time because the program has already established that ch is a space and hence could not be a newline. Version 2, in the same situation, skips the newline test.

2

Both ++ch and ch + 1 have the same numerical value. But ++ch is type char and prints as a character, while ch + 1, because it adds a char to an int, is type int and prints as a number.

注:另外,++ch导致ch增1,而ch + 1并没有改变ch

3

#include <iostream>
using namespace std;
int main()
{
    char ch;
    int ct1, ct2;

    ct1 = ct2 = 0;
    while ((ch = cin.get()) != '$')
    {
        cout << ch;
        ct1++;
        if (ch = '$')
            ct2++;
        cout << ch;
    }
    cout << "ct1 = " << ct1 << ", ct2 = " << ct2 << "\n";

    return 0;
}

控制台效果截图(细体表示输入,粗体表示输出):

Because the program uses ch = '$' instead of ch == '$', the combined input and output looks like above. Each character is converted to the $ character before being printed the second time. Also the value of the expression ch = $ is the code for the $ character, hence nonzero, hence true; so ct2 is incremented each time.
注:cin.get() 依次从输入流中读入字符H i ! \n S e n d ` `

4

a. weight >= 115 && weight < 125

b. ch == 'q' || ch == 'Q'

c. x % 2 == 0 && x != 26

d. x % 2 == 0 && x % 26 == 0

e. donation >= 1000 && donation <= 2000 || guest == 1

f. (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')

5

Not necessarily. For example, if x is 10, then !x is 0 and ! ! x is 1. However, if x is a bool variable, then ! ! x is x.

6

(x < 0)? -x : x; or (x >= 0) x : -x;

7

switch (ch)
{
    case 'A': a_grade++;
        break;
    case 'B': b_grade++;
        break;
    case 'C': c_grade++;
        break;
    case 'D': d_grade++;
        break;
    default: f_grade++;
        break;
}

8

If you use integer labels and the user types a noninteger such as q, the program hangs because integer input can't process a character. But if you use character labels and the user types an integer such as 5, character input will process 5 as a character. Then the default part of the switch can suggest entering another character.

9

Here is one version:

int line = 0;
char ch;
while (cin.get(ch) && ch != 'Q')
{
    if (ch == '\n') /* 不等于时 continue 跳出本次循环,相当于等于时,继续执行下面的语句 */
        line++;
}

Programming Exercises

1

#include <iostream>
#include <cctype>

int main()
{
    using namespace std;

    cout << "Enter words: ";
    char ch;
    ch = cin.get();
    while (ch != '@')
    {
        if (!isdigit(ch))
        {
            if (isupper(ch))
                ch = tolower(ch);
            else if (islower(ch))
                ch = toupper(ch);

            cout << ch;
        }
        cin.get(ch);
    }

    return 0;
}

2

#include <iostream>
const int ArSize = 10;

int main()
{
    using namespace std;

    double arr[ArSize];
    double sum = 0.0;
    double aver = 0.0;
    int count = 0;

    cout << "Enter 10 donotion values: ";
    for (int i = 0; i < ArSize; ++i)
    {
        cin >> arr[i];
        sum += arr[i];
    }

    aver = sum / ArSize;
    cout << "Average: " << aver << endl;

    for (int i = 0; i < ArSize; ++i)
    {
        if (arr[i] > aver)
            ++count;
    }
    cout << count << " numbers in the array are larger than the average.\n";

    return 0;
}

3

#include <iostream>

int main()
{
    using namespace std;

    char ch;

    cout << "Please enter one of the following choices:\n"
         << "c) carnivore                  p) pianis\n"
         << "t) tree                       g) game\n"
         << "f\n";

    cin >> ch; /* cin.get(ch)只会读输入流的第一个字符,其它字符还在输入流待下次读取 */
    while (ch != 'c' && ch != 'p' && ch != 't' && ch != 'g')
    {
        cout << "Please enter a c, p, t, or g: ";
        cin >> ch;
    }

    switch (ch)
    {
        case 'c':
            cout << "A tiger is a carnivore.\n";
            break;
        case 'p':
            cout << "Beethoven is a pianist.\n";
            break;
        case 't':
            cout << "A maple is a tree.\n";
            break;
        case 'g':
            cout << "LOL is a game.\n";
            break;
    }

    return 0;
}

4

#include <iostream>
const int STRSIZE = 20;
const int MEMBERS = 5;
enum {FULLNAME, TITLE, BOPNAME};

struct bop {
    char fullname[STRSIZE]; // real name
    char title[STRSIZE]; // job title
    char bopname[STRSIZE]; // secret BOP name
    int preference; // 0 = fullname, 1 = title, 2 = bopname
};

int main()
{
    using namespace std;

    bop members[MEMBERS] = {
        {"Wimp Macho", "Game Designer", "WIMPY", FULLNAME},
        {"Raki Rhodes", "Junior Programmer", "RAR", TITLE},
        {"Celia Laiter", "Operation Engineer", "MIPS", BOPNAME},
        {"Hoppy Hipman", "Analyst Trainee", "HAHA", TITLE},
        {"Pat Hand", "Code Analyst", "LOOPY", BOPNAME}
    };

    cout << "Benevolent Order of Programmers Report\n"
         << "a. display by name          b. display by title\n"
         << "c. display by bopname       d. display by preference\n"
         << "q. quit\n"
         << "Enter your choice: ";

    char choice;
    int i;
    cin >> choice;
    while (choice != 'q')
    {
        switch (choice)
        {
            case 'a':
                for (i = 0; i < MEMBERS; ++i)
                    cout << members[i].fullname << endl;
                break;
            case 'b':
                for (i = 0; i < MEMBERS; ++i)
                    cout << members[i].title << endl;
                break;
            case 'c':
                for (i = 0; i < MEMBERS; ++i)
                    cout << members[i].bopname << endl;
                break;
            case 'd':
                for (i = 0; i < MEMBERS; ++i)
                    switch (members[i].preference)
                    {
                        case FULLNAME:
                            cout << members[i].fullname << endl;
                            break;
                        case TITLE:
                            cout << members[i].title << endl;
                            break;
                        case BOPNAME:
                            cout << members[i].bopname << endl;
                            break;
                    }
                break;
        }

        cout << "Next choice: ";
        cin >> choice;
    }
    cout << "Bye!\n";

    return 0;
}

5

#include <iostream>
#include <cctype>

int main()
{
    using namespace std;

    double income;
    double tax;

    cout << "Enter your income (enter a negative number or non-numeric will quit): ";
    cin >> income;
    while (income >= 0.0 && !isascii(income))
    {
        tax = 0.0;

        /* 低于5000不收税;5001~15000收10%税;15000~35000收15%税;大于35000部分收20%税,所以分界点为35000、15000和5000 */
        if (income > 35000.0)
            tax += (income - 35000.0) * 0.2 + 20000.0 * 0.15 + 10000.0 * 0.1;
        else if (income > 15000.0)
            tax += (income - 15000.0) * 0.15 + 10000 * 0.1;
        else if (income > 5000.0)
            tax += (income - 5000.0) * 0.1;

        cout << "Tax = " << tax << endl;

        cout << "Enter your income (enter a negative number or non-numeric will quit): ";
        cin >> income;
    }
    cout << "Bye!\n";

    return 0;
}

double min(double a, double b)
{
    return a < b ? a : b;
}

6

#include <iostream>
#include <string>

struct Patron
{
    std::string name;
    double donation;
};

int main()
{
    using namespace std;

    int n;
    cout << "Enter the number of patrons: ";
    cin >> n;
    Patron * patrons = new Patron[n];
    int i;
    int grand_patrons = 0;
    for (i = 0; i < n; ++i)
    {
        cout << "Enter the name of patron " << i + 1 << ": ";
        cin >> patrons[i].name; // 此处读入的名字不包含任何空字符(空格、tab)
        cout << "Enter the donation of patron " << i + 1 << ": ";
        cin >> patrons[i].donation;
        if (patrons[i].donation > 10000.0)
            grand_patrons++;
    }

    cout << "Grand Patrons:\n";
    if (grand_patrons == 0)
        cout << "none\n";
    else
        for (i = 0; i < n; ++i)
            if (patrons[i].donation > 10000.0)
                cout << "Name: " << patrons[i].name
                << ", Donation: " << patrons[i].donation << endl;

    cout << "Patrons:\n";
    if (grand_patrons == n || n == 0)
        cout << "none\n";
    else
        for (i = 0; i < n; ++i)
            if (patrons[i].donation <= 10000.0)
                cout << "Name: " << patrons[i].name
                     << ", Donation: " << patrons[i].donation << endl;

    delete [] patrons;
    return 0;
}

7

#include <iostream>
#include <cctype>
#include <string>

int main()
{
    using namespace std;

    string words;
    int vowels = 0;
    int consonants = 0;
    int others = 0;

    cout << "Enter words (q to quit):\n";

    while (cin >> words)
    {
        if (words[0] == 'q' || words[0] == 'Q')
            break;
        else if (isalpha(words[0]))
            switch (words[0])
            {
                case 'a':
                case 'A':
                case 'o':
                case 'O':
                case 'e':
                case 'E':
                case 'i':
                case 'I':
                case 'u':
                case 'U':
                    vowels++;
                    break;
                default:
                    consonants++;
                    break;
            }
            else
                others++;
    }

    cout << vowels << " words beginning with vowels\n"
    << consonants << " words beginning with consonants\n"
    << others << " others\n";

    return 0;
}

8

#include <iostream>
#include <fstream> // for file I/O

int main()
{
    using namespace std;

    ifstream inFile;
    inFile.open("/Users/gemingdai/Desktop/DS/test"); // “test :I love Apple!” 算上空格正好13个字符
    int count = 0;

    if (!inFile.is_open())
    {
        cout << "Can't open file\n";
        exit(EXIT_FAILURE); // same as return 1
    }

    inFile.get();
    while (!inFile.eof())
    {
        inFile.get();
        ++count;
    }
    cout << "The file cotains " << count << " characters.\n";

    inFile.close();
    return 0;
}

9

#include <iostream>
#include <fstream> // for file I/O
#include <cstdlib>

struct Patron
{
    char name[20];
    double donation;
};

int main()
{
    using namespace std;

    int num;
    ifstream inFile;
    inFile.open("/Users/gemingdai/Desktop/DS/test");

    if (!inFile.is_open())
    {
        cout << "Can't open file\n";
        exit(EXIT_FAILURE); // same as return 1
    }

    inFile >> num;
    inFile.get();
    Patron * pd = new Patron[num];
    for(int i = 0; i < num; ++i)
    {
        inFile.getline(pd[i].name, 20);
        inFile >> pd[i].donation;
        cout << "Name: " << pd[i].name << ", Donation: " << pd[i].donation << endl;
        inFile.get();
    }

    inFile.close();
    return 0;
}

c++-pimer-plus-6th-chapter06的更多相关文章

  1. The 6th tip of DB Query Analyzer

      The 6th tip of DB Query Analyzer MA Gen feng (Guangdong Unitoll Services incorporated, Guangzhou ...

  2. [转载]ECMA-262 6th Edition / Draft August 24, 2014 Draft ECMAScript Language Specification

    http://people.mozilla.org/~jorendorff/es6-draft.html#sec-23.4 Draft Report Errors and Issues at: htt ...

  3. chapter06

    /** * Created by EX-CHENZECHAO001 on 2018-03-30. */class Chapter06 { } // 6 对象// 用对象作为单例或存放工具的方法// 类 ...

  4. Chapter06 数组(Array)

    目录 Chapter06 数组 6.1 数组的认识 6.2 数组的使用 使用方式1 - 动态初始化 使用方式2 - 动态初始化 使用方法3 - 静态初始化 6.3 数组使用的注意事项和细节 6.4 数 ...

  5. ​Si2151/41 6th Generation Silicon TV Tuner ICs

    ​ The Si2151/41 are the industry's most advanced silicon TV tuner ICs supporting all worldwide terre ...

  6. Codeforces Round #361 Jul.6th B题 ☺译

    最近迈克忙着考前复习,他希望通过出门浮躁来冷静一下.迈克所在的城市包含N个可以浮躁的地方,分别编号为1..N.通常迈克在家也很浮躁,所以说他家属于可以浮躁的地方并且编号为1.迈克从家出发,去一些可以浮 ...

  7. Codeforces Round #361 Jul.6th A题 ☺译

    A.迈克和手机 当迈克在沙滩上游泳的时候,他意外的把他的手机扔进了水里.不过你甭担心因为他立马买了个便宜些的代替品,这个代替品是老款九键键盘,这个键盘只有十个等大的数字按键,按以下方式排列: 1 2 ...

  8. October 6th 2016 Week 41st Thursday

    The outer world you see is a reflection of your inner self. 你拥有什么样的内心,你就会看到什么样的世界. And we eventually ...

  9. September 6th 2016 Week 37th Tuesday

    I only wish to face the sea, with spring flowers blossoming. 我只愿面朝大海,春暖花开. That scenery is beautiful ...

  10. July 6th, Week 28th Wednesday, 2016

    Diligence is the mother of good fortune. 勤勉是好运之母. The mother of good fortune can be diligence, conti ...

随机推荐

  1. ThreadPoolExecutor线程池

    为什么使用线程池: 1.创建/销毁线程伴随着系统开销,过于频繁的创建/销毁线程,会很大程度上影响处理效率. 2.线程并发数量过多,抢占系统资源从而导致阻塞. 3.对线程进行一些简单的管理. 在java ...

  2. upc组队赛1 不存在的泳池【GCD】

    不存在的泳池 题目描述 小w是云南中医学院的同学,有一天他看到了学校的百度百科介绍: 截止到2014年5月,云南中医学院图书馆纸本藏书74.8457万册,纸质期刊388种,馆藏线装古籍图书1.8万册, ...

  3. CodeForces 459C Pashmak and Buses(构造)题解

    题意:n个人,k辆车,要求d天内任意两人都不能一直在同一辆车,能做到给出构造,不能输出-1 思路:我们把某一个人这d天的车号看成一个d位的数字,比如 1 1 2 3代表第一天1号车.第二天1号车.第三 ...

  4. Python中的open和codecs.open

    最近老被编码困扰,多次折腾之后,感觉python的编解码做得挺好的,只要了解下边的流程,一般都能解决 input文件(gbk, utf-8...) ----decode-----> unicod ...

  5. Unsupervised Image-to-Image Translation Networks --- Reading Writing

    Unsupervised Image-to-Image Translation Networks --- Reading Writing 2017.03.03 Motivations: most ex ...

  6. .Net Core Package lose or not match

    错误.警告的说明: 示例一: 严重性:警告 代码:MSB3106 说明 :程序集强名称“C:\Users\$(computerName)\.nuget\packages\$(packageName)\ ...

  7. 安装 Linux 内核 4.0

    大家好,今天我们学习一下如何从Elrepo或者源代码来安装最新的Linux内核4.0.代号为‘Hurr durr I'm a sheep’的Linux内核4.0是目前为止最新的主干内核.它是稳定版3. ...

  8. python学习 day013打卡 内置函数

    本节主要内容: 内置函数: 内置函数就是python给你提供的.拿来直接用的函数,比如print,input等等.截止到python版本3.6.2 python一共提供了68个内置函数.他们就是pyt ...

  9. hdu 1392 Surround the Trees 凸包裸题

    Surround the Trees Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Other ...

  10. WAI-ARIA无障碍网页应用属性完全展示

    本文为原创辛苦之作,尊重劳动,转载请注明来自张鑫旭-鑫空间-鑫生活[http://www.zhangxinxu.com]本文地址:http://www.zhangxinxu.com/wordpress ...