[C++ Primer Plus] Chapter 6 Branch Statements and Logical Operators

6.1 if statement

if syntax: if (test-condition) statement
if test condition will be coerced to bool value, so 0 will be converted to false and non-zero to true.

6.2 if-else statement

6.3 if else if else structure

Since the if else statement itself is a statement, it can be placed after the else.

// ifelseif.cpp -- using if else if else

#include <iostream>

const int Fave = 27;

int main()
{
    
    
    using namespace std;
    int n;
    cout << "Enter a number in the range 1-100 to find ";
    cout << "my favorite number: ";
    do
    {
    
    
        cin >> n;
        if (n < Fave)
            cout << "Too low -- guess again: ";
        else if (n > Fave)
            cout << "Too high -- guess again: ";
        else
            cout << Fave << " is right!\n";
    } while (n != Fave);
    return 0;
}

6.4 Logical Operators: &&, ||, and !

6.4.1 Logical OR operator: ||

  1. Logical || has lower precedence than relational operators
  2. The resulting expression evaluates to true if any or all of the original expressions are true (or nonzero); otherwise, the expression evaluates to false.
  3. Modify the value on the left first, and then judge the value on the right. ( i++ < 6||i== jAssuming that i originally had the value 10, when i and j are compared, i will have the value 11.)
  4. If the expression on the left is true, C++ will not judge the expression on the right, because as long as one expression is true, the entire logical expression is true.

6.4.2 Logical AND operator: &&

  1. Logical && has lower precedence than relational operators
  2. The logical AND operator has higher precedence than the logical OR operator.
  3. The resulting expression evaluates to true only if both original expressions are true.
  4. If the left side is false, the entire logical expression must be false, in which case C++ will no longer judge the right side.
  5. The && operator also allows the creation of a series of if else if else statements, each of which corresponds to a specific range of values

6.4.3 Logical NOT operator: !

  1. The ! operator negates the truth value of the expression following it.
  2. The ! operator has precedence over all relational and arithmetic operators.
// (将!运算符用于函数返回值)来筛选可 赋给int变量的数字输入。

#include <iostream>
#include <climits>      // 注意这里要加上头文件,定义了符号常量(INT_MAX和INT_MIN)

bool in_num(double n);

int main(void)
{
    
    
    using namespace std;

    cout << "Enter a number:";
    double num;     // 注意这里要定义成 double 类型的输入,取值范围比int大
    cin >> num;
    while (!in_num(num))
    {
    
    
        cout << "Enter against:";
        cin >> num;
    }
    int value = (int) num;
    cout << "you have entered the integer " << value << endl;

    return 0;
}

bool in_num(double n)
{
    
    
    if (n <= INT_MAX && n >= INT_MIN)
        return true;
    else
        return false;
}

out

Enter a number:6234128679
Enter against:135
you have entered the integer 135

6.5 cctype character library

  1. It can simplify tasks such as determining whether a character is an uppercase letter, a number, punctuation, etc. The prototypes of these functions are defined in the header file cctype (ctype.h in the old style).
  2. isalpha(ch)For example, the function returns a nonzero value if ch is a letter, and 0 otherwise.
  3. ispunct(ch)Likewise, the function will return true if ch is a punctuation character such as a comma or period .
  4. The return type of these functions is int, not bool.

Use AND and OR to test whether the character ch is the code of an alphabetic character: if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
use isalpha( ) to test whether the character ch is the code of an alphabetic character: if (isalpha(ch))
some ctype library functions

  • isalnum() This function returns true if the argument is alphanumeric, that is, letters or numbers
  • isalpha() returns true if the argument is a letter
  • isblank() returns true if the argument is a blank or a horizontal tab
  • iscntrl() returns true if the argument is a control character
  • isdigit() If the parameter is a number (0~9), the function returns true
  • isgraph() returns true if the argument is a printing character other than spaces
  • islower() This function returns true if the argument is a lowercase letter
  • isprint() returns true if the argument is a print character (including spaces)
  • ispunct() returns true if the argument is a punctuation mark
  • isspace() returns true if the argument is a standard whitespace character, such as a space, feed, line feed, carriage return, horizontal tab, or vertical tab
  • isupper() This function returns true if the argument is an uppercase letter
  • isxdigit() If the parameter is a hexadecimal number, that is, 0~9, a f, A F, this function returns true
  • tolower() returns the lowercase if the argument is an uppercase character, otherwise returns the argument
  • toupper() returns the uppercase if the argument is a lowercase letter, otherwise returns the argument
// 使用isalpha( )来检 查字符是否为字母字符,
// 使用isdigits( )来测试字符是否为数字字符,如 3,
// 使用isspace( )来测试字符是否为空白,如换行符、空格和制表符,
// 使用ispunct( )来测试字符是否为标点符号。
// 该程序还复习了if else if结 构,并在一个while循环中使用了cin.get(char)。

#include <iostream>
#include <cctype>

int main(void)
{
    
    
    using namespace std;

    cout << "Enter text for analysis, and type @ to terminate input.\n";
    char ch;
    int whitespace = 0, digits = 0, chars = 0, punct = 0, others = 0;
    cin.get(ch);
    while (ch != '@')
    {
    
    
        if (isalpha(ch))
            chars++;
        else if (isspace(ch))
            whitespace++;
        else if (isdigit(ch))
            digits++;
        else if (ispunct(ch))
            punct++;
        else
            others++;
        cin.get(ch);
    }
    cout << chars << " letters, " << whitespace << " whitespace, " << digits << " digits, "
         << punct << " punctuations, " << others << " others.\n" << endl;

    return 0;
}

6.6 Conditional Operators: ? :

Syntax: The expression1 ? expression2 : expression3
operator used to replace the if else statement is the only operator in C++ that requires 3 operands.
If expression1 is true, the entire conditional expression evaluates to the value of expression2; otherwise, the entire expression evaluates to the value of expression3.

// 条件运算符生成一个表达式,因此是一个值,可以将其赋给变量或将其放到一个更大的表达式中

#include <iostream>

int main(void)
{
    
    
    using namespace std;

    int a, b;
    cout << "Enter two int:";
    cin >> a >> b;
    int c = a>b ? a : b;    // 条件运算符生成一个表达式,因此是一个值,可以将其赋给变量或将其放到一个更大的表达式中
    cout << "c = " << c << endl;

    return 0;
}

6.7 switch statement

switch statement format :

switch (integer-expression) {
    
    
    case label1 : statement(s)
    case label2 : statement(s)
    ...
    default : statement(s)
}
  1. When the switch statement is executed, the program will jump to the line marked with the value of the integer-expression. For example, if the value of integer-expression is 4, the program will execute the line labeled case 4:.
  2. As the name implies, integer-expression must be an expression that results in an integer value. Additionally, each label must be an integer constant expression. The most common labels are int or char constants (such as 1 or 'q'), but can also be enumerators. The switch statement promotes the enumerator to an int when it compares the int value to the enumerator label.
  3. If integer-expression does not match any label, the program will skip to the line labeled default. The Default label is optional. If it is omitted and there is no matching label, the program will jump to the statement after the switch.
  4. After the program jumps to a specific line of code in the switch, all subsequent statements will be executed sequentially, unless there are specific instructions otherwise. The program will not stop automatically when it reaches the next case. To make the program stop after executing a set of specific statements, the break statement must be used. This will cause the program to jump to the statement following the switch.
// 如何使用switch和break来让用户选择简单菜单。
// 该程序使用showmenu( )函数显示一组选项,然后使用switch语句, 根据用户的反应执行相应的操作。
// 使用字符(而不是整数)作为菜单选项和switch标签,则可以为大写标签和小写标签提供相同的语句

#include <iostream>
using namespace std;

void showmenu();
void report();
void comfort();

int main(void)
{
    
    
    showmenu();
    int choice;
    cin >> choice;
    while(choice != 5)  // 当用户输入了5时,while循环结束。输入1到4将执行switch列表中 相应的操作,输入6将执行默认语句。
    {
    
    
        switch(choice)
        {
    
    
            case 1 : cout << "\a\n"; break;
            case 2 : report(); break;
            case 3 : cout << "The boss was in all day.\n"; break;
            case 4 : comfort(); break;
            default : cout << "That's not a choice.\n";
        }
        showmenu();
        cin >> choice;
    }
    cout << "Bye!\n";

    return 0;
}

void showmenu()
{
    
    
    cout << "Please enter 1, 2, 3, 4, or 5 :\n"
            "1) alarm   2) report\n"
            "3) alibi   4) comfort  5) quit\n";
}

void report()
{
    
    
    cout << "I LOVE YOU!\n";
}

void comfort()
{
    
    
    cout << "THINK YOU!\n";
}

6.8 continue and break statements

  1. Both break and continue statements enable a program to skip sections of code.
  2. The break statement can be used in a switch statement or any loop to cause the program to jump to the statement after the switch or loop.
  3. The continue statement is used in a loop to let the program skip the rest of the code in the loop body and start a new loop.
// 该程序让用户输入 一行文本。循环将回显每个字符,如果该字符为句点,则使用break结束循环。
// 这表明,可以在某种条件为true时,使用break来结束循环。
// 接下来,程序计算空格数,但不计算其他字符。当字符不为空格时,循环使用continue语句跳过计数部分。

#include <iostream>
#include <cstring>
const int ArSize = 80;

int main(void)
{
    
    
    using namespace std;

    cout << "Please enter string str:";
    char str[ArSize];
    cin.get(str, ArSize).get();
    cout << "Complete line:\n" << str << endl;
    int space = 0;
    for (int i=0; i < strlen(str); i++)
    {
    
    
        cout << str[i];
        if (str[i] == ' ')
        {
    
    
            space++;
            continue;   // 虽然continue语句导致该程序跳过循环体的剩余部分,但不会跳过循环的更新表达式
        }
        if (str[i] == '.')
            break;
    }
    cout << endl << space << " space\n";
    cout << "Done!";

    return 0;
}

C++ also has a goto statement:

// 下面的语句将跳到使用paris:作为标签的位置:
char ch;
cin >> ch;
if (ch == 'P')
goto paris;
cout << ...
...
paris: cout << "You've just arrived at Paris.\n";

6.9 Loop to read numbers

Both typos and EOF will cause cin to return false. The clear( ) method resets the bad input flag and also resets the end of file.
The expression cin>>fish[i]is actually a function call to the cin method, which returns cin. If cin is in the test condition, it will be converted to bool type. The converted value is true if the input was successful, otherwise false.
When the program finds that the user has entered something wrong, it should take 3 steps:

  1. Reset cin to accept new input.
  2. Delete incorrect entries.
  3. Prompt the user for additional input.
// 假设程序要求用户提供5个高尔夫得分,以计算平均成绩。如果用户输入非数字输入,程序将拒绝,并要求用户继续输入数字。
// 可以看到,可以使用cin输入表达式的值来检测输入是不是数字。

// cingolf.cpp -- non-numeric input skipped
#include <iostream>
const int Max = 5;

int main()
{
    
    
    using namespace std;
// get data
    int golf[Max];
    cout << "Please enter your golf scores.\n";
    cout << "You must enter " << Max << " rounds.\n";
    int i = 0;
    for (i = 0; i < Max; i++)
    {
    
    
        cout << "round #" << i+1 << ": ";
        while (!(cin >> golf[i]))   // 使用cin输入表达式的值来检测输入是不是数字。
        {
    
    
            cin.clear();            // reset input
            while (cin.get() != '\n')
                continue;           // get rid of bad input
            cout << "Please enter an int number:";
        }
    }
// calculate average
    double total = 0.0;
    for (i = 0; i < Max; i++)
        total += golf[i];
// report results
    cout << total / Max << " = average score " << Max << " rounds\n";
    return 0;
}

out:

Please enter your golf scores.
You must enter 5 rounds.
round #1:20
round #2:dk
Please enter an int number:30
round #3:10
round #4:50
round #5:60
34 = average score 5 rounds

6.10 Basic File I/O

#include // ostream->cout istream->cin
#include // ofstream ifstream
#include // support for exit()

6.10.1 cin input

  1. The header file iostream must be included.
  2. The header file iostream defines an istream class for processing input.
  3. The header file iostream declares an istream variable (object) named cin.
  4. The namespace std must be specified; for example, to refer to the element cin, the pragma using or the prefix std:: must be used.
  5. You can use cin in conjunction with the operator >> to read various types of data. You can use the cin and get( ) methods to read a character, and cin and getline( ) to read a line of characters.
  6. You can use cin in combination with eof( ) and fail( ) methods to determine whether the input is successful.
  7. When the object cin itself is used as a test condition, it will be converted to boolean true if the last read operation was successful, and false otherwise.
  8. When using cin for input, the program sees the input as a series of bytes, where each byte is interpreted as a character encoding. Regardless of the target data type, the input starts out as character data—text data. The cin object is then responsible for converting the text to other types.
38.5 19.2	// 输入,输入一开始为文本
    
char ch;
cin >> ch;	// 3  输入行中的第一个字符被赋给ch

int n;
cin >> n;	// 38  直到遇到非数字字符

double x;
cin >> x;	// 38.5  直到遇到第一个不属于浮点数的 字符

char word[50];
cin >> word;	// 38.5  直到遇到空白字符,cin将这4个字符的字符编码存储到数组word中,并在末尾加上一个空字符。

char word[50];
cin.geline(word,50);	// 直到遇到换行符,并在末尾加上一个空字符。换行符被丢弃,输入队列中的下一个字符是下一行中的第一个字符。
int number;
cin >> number;				// 写入一个数字

char ch;
cin >> ch;					// 输入一个字符,不保留空格和换行符

string str, str1[2];
getline(cin, str);			// 写入一个string
getline(cin, str1[1]);		// 写入一个string数组中的一个string变量

char ch[100];
(cin >> ch).get();         //以空白(空格、 制表符和换行符)来确定字符串的结束位置。保留换行符;把回车键生成的换行符留在了输入队列中。
cin.getline(ch, 100);      //每次读取一行字符串输入,丢弃换行符;arraySize(包括结尾字符)。
cin.get(ch, 100).get();    //每次读取一行字符串输入,保留换行符;

char ch;
cin.get(ch);
...							// 然后进行一系列操作
cin.get();					// 消除空行

6.10.2 cout output

  1. The header file iostream must be included.
  2. The header file iostream defines an ostream class for processing output.
  3. The header file iostream declares an ostream variable (object) named cout.
  4. The namespace std must be specified; for example, to refer to the elements cout and endl, the pragma using or the prefix std:: must be used.
  5. You can use cout in conjunction with the operator << to display various types of data.

6.10.3 File output/write to file

  1. The header file fstream must be included.
  2. The header file fstream defines an ofstream class for processing output.
  3. You need to declare one or more ofstream variables (objects), and name them in the way you like, provided that you follow the usual naming rules.
  4. The namespace std must be specified; for example, to refer to the element ofstream, the pragma using or the prefix std:: must be used.
  5. Need to associate the ofstream object with the file. One of the ways to do this is to use the open( ) method.
  6. When finished using a file, it should be closed using the method close( ).
  7. The ofstream object can be used in combination with the operator << to output various types of data.

The main steps of file output:

// 1、包含头文件fstream
#include <iostream> 	// ostream->cout    istream->cin
#include <fstream>  	// ofstream         ifstream

// 2、声明自己的ofstream对象,为其命名
ofstream outFile; 		// outFile an ofstream object 
ofstream fout; 			// fout an ofstream object

// 3、将这种对象与特定的文件关联起来:
outFile.open("fish.txt"); // outFile used to write to the fish.txt file
                          // 打开已有的文件,以接受输出时,默认将它其长度截短为零,因此原来的内容将丢失。
char filename[50];
cin >> filename; 		// user specifies a name
fout.open(filename); 	// fout used to read specified file

// 4、使用cout那样使用该ofstream对象:
double wt = 125.8;
outFile << wt; 			// write a number to fish.txt
char line[81] = "Objects are closer than they appear.";
fout << line << endl; 	// write a line of text

// 5、使用close()关闭文件:
outFile.close();		// done with file
fout.close();			// 方法close( )不需要使用文件名作为参数,这是因为outFile已经同特定的文件关联起来。
                        // 如果您忘记关闭文件,程序正常终止时将自动关闭它。
// 文件输出

#include <iostream> // ostream->cout    istream->cin
#include <fstream>  // ofstream         ifstream

int main(void)
{
    
    
    using namespace std;

    char automoblie[50];
    int year;
    double a_price, d_price;

    ofstream outFile;   // 2、创建对象
    outFile.open("carinfo.txt");    // 3、关联文件,创建文件

    cout << "Enter the make and model of automobile:";
    cin.getline(automoblie, 50);
    cout << "Enter the model year:";
    cin >> year;
    cout << "Enter the origional asking price:";
    cin >> a_price;
    d_price = 0.913 * a_price;

    cout << fixed;        // 不要以科学计数法显示
    cout.precision(2);    // 显示输出精度到小数点后两位
    cout.setf(ios_base::showpoint); // 即使小数点后面为零也显示出来
    cout << "Make and model:" << automoblie << endl;    // 屏幕输出是使用cout的结果
    cout << "Year: " << year << endl;
    cout << "Was asking $" << a_price << endl;
    cout << "Now asking $" << d_price << endl;

    outFile << fixed;
    outFile.precision(2);
    outFile.setf(ios_base::showpoint);
    outFile << "Make and model: " << automoblie << endl;    // 和 cout 使用方法一样,在文本输出
    outFile << "Year: " << year << endl;    // outFile将cout显示到屏幕上的内容写入到了文件 carinfo.txt中
    outFile << "Was asking $" << a_price << endl;
    outFile << "Now asking $" << d_price << endl;

    outFile.close();    // 方法close( )不需要使用文件名作为参数,这是因为outFile已经同特定的文件关联起来。
                        // 如果您忘记关闭文件,程序正常终止时将自动关闭它。

    return 0;
}

out:
image.png

6.10.4 File input/read file

  1. The header file fstream must be included.
  2. The header file fstream defines an ifstream class for processing input.
  3. You need to declare one or more ifstream variables (objects) and name them whatever you like, provided you follow the usual naming rules.
  4. The namespace std must be specified; for example, to refer to the element ifstream, the pragma using or the prefix std:: must be used.
  5. An ifstream object needs to be associated with a file. One of the ways to do this is to use the open( ) method.
  6. When you are done using a file, you should close it with the close( ) method.
  7. Various types of data can be read using the ifstream object in combination with the operator >>.
  8. You can use the ifstream object and the get( ) method to read a character, and the ifstream object and getline( ) to read a line of characters.
  9. You can use ifstream in combination with eof( ), fail( ) and other methods to determine whether the input is successful.
  10. When the ifstream object itself is used as a test condition, it will be converted to boolean true if the last read operation was successful, and false otherwise.

Main steps for file input:

// 1、包含头文件fstream
#include <iostream> 	// ostream->cout    istream->cin
#include <fstream>  	// ofstream         ifstream
#include <cstdlib> 		// support for exit()

// 2、声明ifstream对象,为其命名
ifstream inFile; // inFile an ifstream object
ifstream fin; // fin an ifstream object

// 3、将ifstream对象与特定的文件关联起来
inFile.open("bowling.txt"); // inFile used to read bowling.txt file
char filename[50];			
cin.getline(filename, 50); 	
fin.open(filename); 		// fin used to read specified file
// 方法2-1:string filename;
// 方法2-2:getline(cin, filename);

// 4、检查文件是否被成功打开的首先方法是使用方法is_open( )
inFile.open("bowling.txt");
if (!inFile.is_open())
{
    
    
exit(EXIT_FAILURE);
}
// 如果文件被成功地打开,方法is_open( )将返回true;因此如果文件 没有被打开,表达式!inFile.isopen( )将为true。
// 函数exit( )的原型是在头 文件cstdlib中定义的,在该头文件中,还定义了一个用于同操作系统通 信的参数值EXIT_FAILURE。函数exit( )终止程序。

// 5、使用cin那样使用ifstream对象
double wt;
inFile >> wt; // read a number from bowling.txt
char line[81];
fin.getline(line, 81); // read a line of text

// 6、使用close()关闭文件:
inFile.close();

Check if the file was successfully opened: is_open( )

What happens if you try to open a non-existent file for input? This kind of error will cause failure when using the ifstream object for input later.
The first way to check whether a file was successfully opened is with the method is_open( ):

  1. The method is_open( ) will return true if the file was successfully opened; thus the expression !inFile.isopen( ) will be true if the file was not opened.
  2. The prototype of the function exit( ) is defined in the header file cstdlib. In this header file, a parameter value EXIT_FAILURE for communicating with the operating system is also defined. The function exit( ) terminates the program.
inFile.open("bowling.txt");
if (!inFile.is_open())
{
    
    
	exit(EXIT_FAILURE);
}

Check the file for errors

  1. First, the program should not exceed EOF when reading the file. If EOF was encountered the last time the data was read, the method eof( ) will return true.
  2. The method fail( ) will return true if a type mismatch occurred during the last read operation (it will also return true if EOF was encountered)
  3. If the file is damaged or the hardware is faulty, bad( ) will return true.
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";
  1. good( ) method, which returns true if no errors occurred:
while (inFile.good()) // while input good and not at EOF
{
    
    
...
}

// 表达式inFile >> value的 结果为inFile,而在需要一个bool值的情况下,inFile的结果为 inFile.good( ),即true或false。
inFile >> value; // get first value
while (inFile.good()) // while input good and not at EOF
{
    
    
// loop body goes here
inFile >> value; // get next value
}

// 将两条输入语句用一条用作循环测试的输入语句代替。
// 要计算表达 式inFile >> value的值,程序必须首先试图将一个数字读取到value中。
while (inFile >> value) // read and test for success
{
    
    
// loop body goes here
// omit end-of-loop input
}
// 打开用户指定的文件,读取其中的数字,然后指出文件中包含多少个值以及它们的和与平均值。
// 首先必须创建一个包含数字的文本文件。
// sumafile.cpp -- functions with an array argument

#include <iostream>
#include <fstream>      // file I/O support
#include <cstdlib>      // support for exit()
const int SIZE = 100;
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";
        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
    return 0;
}

image.png
out:
image.png

6.11 Summary

  1. C++ provides if statement, if else statement and switch statement to manage options. The if statement causes the program to execute a statement or block of statements conditionally, that is, the program will execute a particular statement or block of statements if a specific condition is met. The if else statement The program chooses to execute one of two statements or blocks of statements. You can add if else to this statement to provide a range of options. A switch statement directs a program to execute one of a series of options.
  2. C++ also provides operators to help with decision-making. Chapter 5 discusses relational expressions, which compare two values. If and if else statements typically use relational expressions as test conditions. By using logical operators (&&, ||, and !), relational expressions can be combined or modified to create more granular tests. The conditional operator (?:) provides a compact way of selecting one of two values.
  3. The cctype character library provides a set of convenient and powerful tools for analyzing character input.
  4. Loops and select statements are useful tools for file I/O; file I/O is very similar to console I/O. After declaring the ifstream and ofstream objects and associating them with files, you can use them like cin and cout.
  5. Using loops and decision statements, you can write interesting, intelligent, and powerful programs.

6.12 Review Questions

5. In C++, is !!x the same as x?
uncertain. For example: if x=10, then !x=0, !!x=1. However, if x is a bool variable, then !!x is x.

8. Compared with using numbers, what are the advantages of using characters (such as a and c) to represent menu options and case labels?
If an integer label is used, and the user enters a non-integer number (such as q), the program will hang because integer input cannot handle characters. However, if a character label is used, and the user enters an integer such as 5, the character input treats 5 as a character. Then, the default part of the switch statement will prompt for another character.

6.13 Programming Exercises

// 2
// 编写一个程序,最多将10个donation值读入到一个double数组中(如果您愿意,也可使用模板类array)。
// 程序遇到非数字输入时将结束输入,并报告这些数字的平均值以及数组中有多少个数字大于平均值。

#include <iostream>
#include <array>

const int ArSize = 10;

int main(void)
{
    
    
    using namespace std;

    array<double, ArSize> donation;
    double sum = 0.0, average = 0.0;
    int count = 0, bigger = 0;

    cout << "Please enter the double numerial:";

    // ***判断值读入到一个double数组中***
    while ((cin >> donation[count])
    {
    
    
        if (++count == ArSize)
            break;
        cout << "Please enter the double numerial:";
    }

    for (int i=0; i < count; i++)
        sum += donation[i];

    average = sum/count;

    for (int i=0; i < count; i++)
        if (donation[i] > average)
            bigger++;

    cout << average << " number's average." << endl;
    cout << bigger << " numbers are bigger than average." << endl;

    return 0;
}

           
// 3
// 编写一个菜单驱动程序的雏形。该程序显示一个提供4个选项的菜单——每个选项用一个字母标记。
// 如果用户使用有效选项之外的字母 进行响应,程序将提示用户输入一个有效的字母,直到用户这样做为止。
// 然后,该程序使用一条switch语句,根据用户的选择执行一个简单操作。

#include <iostream>

using namespace std;

void menu(void);

int main(void)
{
    
    
    menu();
    char ch;
    cin.get(ch);

    while (ch != 'c' && ch != 'p' && ch != 't' && ch != 'g')
    {
    
    
        cin.get();
        cout << "Please enter c, p, t or g :";
        cin.get(ch);
    }

    switch (ch)
    {
    
    
        case 'c' : cout << "cccccccc\n";break;
        case 'p' : cout << "pppppppp\n";break;
        case 't' : cout << "tttttttt\n";break;
        case 'g' : cout << "gggggggg\n";break;
    }

    return 0;
}

void menu(void)
{
    
    
    cout << "Please enter one of the following choices:\n"
            "c) carnivore \tp) pianist\n"
            "t) tree      \tg) game\n";
}
           

// 4
// 加入Benevolent Order of Programmer后,在BOP大会上,人们便可以通过加入者的真实姓名、头衔或秘密BOP姓名来了解他(她)。
// 请编写一个程序,可以使用真实姓名、头衔、秘密姓名或成员偏好来列出成员。编写该程序时,请使用下面的结构:

#include <iostream>

void menu(void);
void display(char ch);

using namespace std;

const int strsize = 40;
const int usersize = 5;

// 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
};

bop user[usersize] =
        {
    
    
                {
    
    "Wimp Macho", "AA", "AAA", 0},
                {
    
    "Raki Rhodes", "BB", "BBB", 1},
                {
    
    "Celia Laiter", "CC", "CCC", 2},
                {
    
    "Hoppy Hipman", "DD", "DDD", 0},
                {
    
    "Pat Hand", "EE", "EEE", 1}
        };

int main(void)
{
    
    
    menu();
    char input;
    cin.get(input);
    while (input != 'q')
    {
    
    
        display(input);
        cin.get();  // 消耗回车
        cin.get(input);
    }
    cout << "Bye!" << endl;

    return 0;
}

void menu(void)
{
    
    
    cout << "a. display by name    \tb. display by title\n"
            "c. display by bopname \td. display by preference\n"
            "q. quit\n";
}

void display(char ch)
{
    
    
    switch (ch)
    {
    
    
        case 'a' :
            for (int i=0; i<usersize; i++)
                cout << user[i].fullname << endl;
            break;
        case 'b' :
            for (int i=0; i<usersize; i++)
                cout << user[i].title << endl;
            break;
        case 'c' :
            for (int i=0; i<usersize; i++)
                cout << user[i].bopname << endl;
            break;
        case 'd' :
            for (int i=0; i<usersize; i++)
            {
    
    
                if (user[i].preference==0)
                    cout << user[i].fullname << endl;
                else if (user[i].preference==1)
                    cout << user[i].title << endl;
                else if (user[i].preference==2)
                    cout << user[i].bopname << endl;
            }
            break;
        default :
            if (ch == 'a' || ch == 'b' || ch == 'c' || ch == 'd')
                cout << "Next choice:";
            else
                cout << "Please enter character a, b, c, d or q :";
    }
}
           
// 5000 tvarps:不收税
// 5001~15000 tvarps:10%
// 15001~35000 tvarps:15%
// 35000 tvarps以上:20%
// 例如,收入为38000 tvarps时,所得税为5000 0.00 + 10000 0.10 + 20000 0.15 + 3000 0.20,即4600 tvarps。
// 请编写一个程序,使用循环来 要求用户输入收入,并报告所得税。当用户输入负数或非数字时,循环将结束。

#include <iostream>

using namespace std;

int main(void)
{
    
    
    float tvarps, tax;
    cout << "Please enter tvarps:";
    while ((cin >> tvarps) && (tvarps >= 0))
    {
    
    
        if (tvarps <= 5000)
            tax = 0;
        else if (tvarps > 5000 && tvarps <= 15000)
            tax = (tvarps-5000) * 0.1;
        else if (tvarps > 15000 && tvarps <= 35000)
            tax = 10000 * 0.10 + (tvarps-15000) * 0.15;
        else
            tax = 10000 * 0.10 + 20000 * 0.15 + (tvarps-35000) * 0.2;
        cout << tax << endl;
        cout << tvarps-tax << endl;
    }

    return 0;
}
// 6
// 编写一个程序,记录捐助给“维护合法权利团体”的资金。
// 该程序要求用户输入捐献者数目,然后要求用户输入每一个捐献者的姓名和款项。
// 这些信息被储存在一个动态分配的结构数组中。每个结构有两个成员:用来储存姓名的字符数组(或string对象)和用来存储款项的 double成员。
// 读取所有的数据后,程序将显示所有捐款超过10000的捐款者的姓名及其捐款数额。该列表前应包含一个标题,指出下面的捐款者是重要捐款人(Grand Patrons)。
// 然后,程序将列出其他的捐款者,该列表要以Patrons开头。
// 如果某种类别没有捐款者,则程序将打印单词“none”。该程序只显示这两种类别,而不进行排序。

#include <iostream>
#include <cstring>

using namespace std;

const int namesize = 20;

struct donation
{
    
    
    string name;
    double money;
};

int main(void)
{
    
    
    int number = 0;
    cout << "Please enter number:";
    cin >> number;
    cin.get();

    donation *ps = new donation[namesize];
    for (int i=0; i < number; i++)
    {
    
    
        cout << "donor #" << i+1 << ": \n";
        cout << "Enter name :";
        getline(cin, ps[i].name);
        cout << "Enter money :";
        cin >> ps[i].money;
        cin.get();
    }

    bool empty = true;

    cout << "Grand Patrons :" << endl;
    for (int i=0; i < number; i++)
    {
    
    
        if (ps[i].money > 10000)
        {
    
    
            cout << ps[i].name << "\t" << ps[i].money << endl;
            empty = false;
        }
    }
    if (empty == true)
        cout << "None.\n";

    empty = true;
    cout << "Patrons :" << endl;
    for (int i=0; i < number; i++)
    {
    
    
        if (ps[i].money <= 10000)
        {
    
    
            cout << ps[i].name << "\t" << ps[i].money << endl;
            empty = false;
        }
    }
    if (empty == true)
        cout << "None.\n";

    delete [] ps;

    return 0;
}
// 7
// 编写一个程序,它每次读取一个单词,直到用户只输入q。
// 然后,该程序指出有多少个单词以元音打头,有多少个单词以辅音打头,还有多少个单词不属于这两类。
// 为此,方法之一是,使用isalpha( )来区分以字母和其他字符打头的单词,
// 然后对于通过了isalpha( )测试的单词,使用if或switch语句来确定哪些以元音打头。

#include <iostream>
#include <cctype>
#include <cstring>

int main(void)
{
    
    
    using namespace std;

    int vowels = 0, consonants = 0, others = 0;
    string words;
    cout << "Enter words (q to quit):";

    while ((cin >> words) && (words != "q"))    // string 用双引号
    {
    
    
        if (isalpha(words[0]))
        {
    
    
            switch (words[0])   // char 用单引号
            {
    
    
                case 'a' : case 'e' : case 'i' : case 'o' : case 'u' :
                case 'A' : case 'E' : case 'I' : case 'O' : case 'U' : vowels++;
                default : consonants++;
            }
        }
        else
            others++;
    }

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

    return 0;
}
// 8
// 编写一个程序,它打开一个文件文件,逐个字符地读取该文件,直到到达文件末尾,然后指出该文件中包含多少个字符。

#include <iostream> 	// ostream->cout    istream->cin
#include <fstream>  	// ofstream         ifstream
#include <cstdlib> 		// support for exit()

int main(void)
{
    
    
    using namespace std;

    char ch;
    int count;
    char filename[50];

    ifstream inFile;            // inFile an ifstream object

    cout << "Please enter the file name:";
    cin.getline(filename, 50);      // user specifies a name
    inFile.open(filename);      // inFile used to read specified file

    if (!inFile.is_open())      // 检查文件是否被成功打开的首先方法是使用方法is_open( )
    {
    
    
        cout << "Filed to open the file." << endl;
        exit(EXIT_FAILURE);
    }

    while (!inFile.eof())
    {
    
    
        inFile >> ch;
        count++;
    }

    cout << filename << " havs " << count << " characters." << endl;

    inFile.close();

    return 0;
}
// 完成编程练习6,但从文件中读取所需的信息。该文件的第一项 应为捐款人数,余下的内容应为成对的行。
// 在每一对中,第一行为捐款 人姓名,第二行为捐款数额。即该文件类似于下面:

#include <fstream>
#include <iostream>
#include <cstring>
#include <cstdlib>      // support for exit()

using namespace std;

const int namesize = 20;

struct donation
{
    
    
    string name;
    double money;
};

int main(void)
{
    
    
    ifstream inFile;

    char filename[50];
    cout << "Please enter the file name:";
    cin.getline(filename, 50);  // user specifies a name
    inFile.open(filename);      // inFile used to read specified file

    if (!inFile.is_open())      // 检查文件是否被成功打开的首先方法是使用方法is_open( )
    {
    
    
        cout << "Filed to open the file." << endl;
        exit(EXIT_FAILURE);
    }

    int number = 0;
    inFile >> number;
    if (number <= 0)
        exit(EXIT_FAILURE);
    cout << "number:" << number << endl;
    inFile.get();

    donation *ps = new donation[namesize];

    int i = 0;
    while ((!inFile.eof()) && (i < number))
    {
    
    
        cout << "donor #" << i+1 << ": \n";
        getline(inFile, ps[i].name);
        cout << "Read name:" << ps[i].name << endl;
        inFile >> ps[i].money;
        cout << "Read money:" << ps[i].money << endl;
        i++;
        inFile.get();   // 再读取一次然后,判断是否到文件末尾
    }

    bool empty = true;

    cout << "Grand Patrons :" << endl;
    for (int i=0; i < number; i++)
    {
    
    
        if (ps[i].money > 10000)
        {
    
    
            cout << ps[i].name << "\t" << ps[i].money << endl;
            empty = false;
        }
    }
    if (empty == true)
        cout << "None.\n";

    empty = true;
    cout << "Patrons :" << endl;
    for (int i=0; i < number; i++)
    {
    
    
        if (ps[i].money <= 10000)
        {
    
    
            cout << ps[i].name << "\t" << ps[i].money << endl;
            empty = false;
        }
    }
    if (empty == true)
        cout << "None.\n";

    delete [] ps;

    return 0;
}

Guess you like

Origin blog.csdn.net/qq_39751352/article/details/126659313