Читаем C++ Primer Plus полностью

// Version 1

while (cin.get(ch))    // quit on eof

{

      if (ch == ' ')

             spaces++;

      if (ch == '\n')

            newlines++;

}

// Version 2

while (cin.get(ch))    // quit on eof

{

      if (ch == ' ')

            spaces++;

      else if (ch == '\n')

            newlines++;

}

What advantages, if any, does the second form have over the first?

2. In Listing 6.2, what is the effect of replacing ++ch with ch+1?

3. Carefully consider the following program:

#include

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;

}

Suppose you provide the following input, pressing the Enter key at the end of each line:

Hi!

Send $10 or $20 now!

What is the output? (Recall that input is buffered.)

4. Construct logical expressions to represent the following conditions:

a. weight is greater than or equal to 115 but less than 125.

b. ch is q or Q.

c. x is even but is not 26.

d. x is even but is not a multiple of 26.

e. donation is in the range 1,000–2,000 or guest is 1.

f. ch is a lowercase letter or an uppercase letter. (Assume, as is true for ASCII, that lowercase letters are coded sequentially and that uppercase letters are coded sequentially but that there is a gap in the code between uppercase and lowercase.)

5. In English, the statement “I will not not speak” means the same as “I will speak.” In C++, is !!x the same as x?

6. Construct a conditional expression that is equal to the absolute value of a variable. That is, if a variable x is positive, the value of the expression is just x, but if x is negative, the value of the expression is -x, which is positive.

7. Rewrite the following fragment using switch:

if (ch == 'A')

    a_grade++;

else if (ch == 'B')

    b_grade++;

else if (ch == 'C')

    c_grade++;

else if (ch == 'D')

    d_grade++;

else

    f_grade++;

8. In Listing 6.10, what advantage would there be in using character labels, such as a and c, instead of numbers for the menu choices and switch cases? (Hint: Think about what happens if the user types q in either case and what happens if the user types 5 in either case.)

9. Consider the following code fragment:

int line = 0;

char ch;

while (cin.get(ch))

{

    if (ch == 'Q')

           break;

    if (ch != '\n')

           continue;

    line++;

}

Rewrite this code without using break or continue.

Programming Exercises

1. Write a program that reads keyboard input to the @ symbol and that echoes the input except for digits, converting each uppercase character to lowercase, and vice versa. (Don’t forget the cctype family.)

2. Write a program that reads up to 10 donation values into an array of double. (Or, if you prefer, use an array template object.) The program should terminate input on non-numeric input. It should report the average of the numbers and also report how many numbers in the array are larger than the average.

3. Write a precursor to a menu-driven program. The program should display a menu offering four choices, each labeled with a letter. If the user responds with a letter other than one of the four valid choices, the program should prompt the user to enter a valid response until the user complies. Then the program should use a switch to select a simple action based on the user’s selection. A program run could look something like this:

Please enter one of the following choices:

c) carnivore           p) pianist

t) tree                g) game

f

Please enter a c, p, t, or g: q

Please enter a c, p, t, or g: t

A maple is a tree.

4. When you join the Benevolent Order of Programmers, you can be known at BOP meetings by your real name, your job title, or your secret BOP name. Write a program that can list members by real name, by job title, by secret name, or by a member’s preference. Base the program on the following structure:

// Benevolent Order of Programmers name structure

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

};

In the program, create a small array of such structures and initialize it to suitable values. Have the program run a loop that lets the user select from different alternatives:

a. display by name     b. display by title

c. display by bopname  d. display by preference

q. quit

Note that “display by preference” does not mean display the preference member; it means display the member corresponding to the preference number. For instance, if preference is 1, choice d would display the programmer’s job title. A sample run may look something like the following:

Benevolent Order of Programmers Report

a. display by name     b. display by title

c. display by bopname  d. display by preference

q. quit

Enter your choice: a

Wimp Macho

Raki Rhodes

Celia Laiter

Hoppy Hipman

Pat Hand

Next choice: d

Wimp Macho

Junior Programmer

MIPS

Analyst Trainee

LOOPY

Next choice: q

Bye!

5. The Kingdom of Neutronia, where the unit of currency is the tvarp, has the following income tax code:

First 5,000 tvarps: 0% tax

Перейти на страницу:

Все книги серии Developer's Library

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных

Похожие книги

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных

Все жанры