目录
本章小结
C++提供了if语句、if else语句和switch语句来管理选项。if语句使程序有条件地执行语句或语句块,也就是说,如果满足特定的条件,程序将执行特定的语句或语句块。if else语句程序选择执行两个语句或语句块之一。可以在这条语句后再加上if else,以提供一系列的选项。switch语句引导程序执行一系列选项之一。
C++还提供了帮助决策的运算符。第5章讨论了关系表达式,这种表达式对两个值进行比较。if和if else语句通常使用关系表达式作为测试条件。通过使用逻辑运算符(&&、||和!),可以组合或修改关系表达式,创建更细致的测试。条件运算符(?:)提供了一种选择两个值之一的简洁方式。
cctype字符函数库提供了一组方便的、功能强大的工具,可用于分析字符输入。
对于文件I/O来说,循环和选择语句是很有用的工具:文件I/O与控制台I/O极其相似。声明ifstream和ofstream对象,并将它们同文件关联起来后,便可以像使用cin和cout那样使用这些对象。
使用循环和决策语句,便可以编写有趣的、智能的、功能强大的程序。
程序清单
6.1 了解if语句
//if.cpp -- using the if statement
#include "stdafx.h"
#include <iostream>
int main()
{
using namespace std;
char ch;
int spaces = 0;
int total = 0;
cin.get(ch);
while (ch != '.')
{
if (ch == ' ')
++spaces;
++total;
cin.get(ch);
}
cout << spaces << " spaces, " << total << " characters total in sentence\n";
return 0;
}
6.2 了解if else语句
// ifelse.cpp -- using the if else statement
#include "stdafx.h"
#include <iostream>
int main()
{
using namespace std;
char ch;
cout << "Type, and I shall repeat.\n";
cin.get(ch);
while (ch != '.')
{
if (ch == '\n')
cout << ch;
else
cout << ++ch;
cin.get(ch);
}
//try ch +1 instead of ++ch for interesting effect
cout << "\nPlease excuse the slight confusion.\n";
return 0;
}
6.3 了解多层else if语句
//ifelseif.cpp -- using if else if else
#include "stdafx.h"
#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 << "Tool 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 了解或运算
//or.cpp -- using the logical OR operator
#include "stdafx.h"
#include <iostream>
int main()
{
using namespace std;
cout << "This program may reformat your hard disk and destroy all your data.\n" << "Don you wish to continue?<y/n>";
char ch;
cin >> ch;
if (ch == 'y' || ch == 'Y')
cout << "You were warned!\a\a\n";
else if (ch == 'n' || ch == 'N')
cout << "A wise choice ... bye\n";
else
cout << "That wasn't a y or n!Apparently you can't follow instructions, so I'll trash your disk anyway.\a\a\a\n";
return 0;
}
6.5 了解与运算
//and.cpp -- using the logical AND operator
#include "stdafx.h"
#include <iostream>
const int ArSize = 6;
int main()
{
using namespace std;
float naaq[ArSize];
cout << "Enter the NAAQs (New Age Awareness Quotients) of your neighbors. Program terminates when you make\n"
<< ArSize << " entries or enter a negative value.\n";
int i = 0;
float temp;
cout << "First value: ";
cin >> temp;
while (i < ArSize && temp >= 0)
{
naaq[i] = temp;
++i;
if (i < ArSize)
{
cout << "Next value: ";
cin >> temp;
}
}
if (i == 0)
cout << "No data--bye\n";
else
{
cout << "Enter your NAAQ: ";
float you;
cin >> you;
int count = 0;
for (int j = 0; j < i; j++)
if (naaq[j] > you)
++count;
cout << count;
cout << " of your neighbors have greater awareness of the New Age than you do.\n";
}
return 0;
}
6.6 了解用&&设置取值范围
//more_and.cpp -- using the logical AND operator
#include "stdafx.h"
#include <iostream>
const char *qualify[4] =
{
"10,000-meter race.\n",
"mud tug-of-war.\n",
"masters canoe jousting.\n",
"pie-throwing festival.\n"
};
int main()
{
using namespace std;
int age;
cout << "Enter your age in years: ";
cin >> age;
int index;
if (age > 17 && age < 35)
index = 0;
else if (age >= 35 && age < 50)
index = 2;
else if (age >= 50 && age < 65)
index = 2;
else
index = 3;
cout << "You qualify for the " << qualify[index];
return 0;
}
6.7 了解否运算
//not.cpp -- using the not operator
#include "stdafx.h"
#include <iostream>
bool is_int(double);
int main()
{
using namespace std;
double num;
cout << "Yo, dude! Enter an integer value: ";
cin >> num;
while (!is_int(num)) //continue while num is not int-able
{
cout << "Out of range -- please try again: ";
cin >> num;
}
int val = int(num); //type cast
cout << "You've entered the integer " << val << "\nBye\n";
return 0;
}
bool is_int(double x)
{
if (x <= INT_MAX && x>= INT_MIN)
return true;
else
return false;
}
6.8 了解一些cctype库函数
// cctypes.cpp -- using the ctype.h library
#include "stdafx.h"
#include <iostream>
#include <cctype>
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
while (ch != '@') //test for sentinel
{
if (isalpha(ch)) //判断是否是字母
chars++;
else if (isspace(ch)) //判断是否为标准空白字符
whitespace++;
else if (isdigit(ch)) //判断是否为16进制
digits++;
else if (ispunct(ch)) //判断是否是标点符号
punct;
else
others++;
cin.get(ch); //get next character
}
cout << chars << " letters, "
<< whitespace << " whitespace, "
<< digits << " digits. "
<< punct << " punctuations, "
<< others << " others.\n";
return 0;
}
6.9 了解? :运算符
// condit.cpp -- using the conditional operator
#include "stdafx.h"
#include <iostream>
int main()
{
using namespace std;
int a, b;
cout << "Enter two integers: ";
cin >> a >> b;
cout << "The larger of " << a << " and " << b;
int c = a > b ? a : b;//c = a if a > b, else c = b
cout << " is " << c << endl;
return 0;
}
6.10 了解 switch语句
//switch.cpp -- using the switch statement
#include "stdafx.h"
#include <iostream>
using namespace std;
void showmenu();
void report();
void comfort();
int main()
{
showmenu();
int choice;
cin >> choice;
while (choice != 5)
{
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\n"
<< "5) quit\n";
}
void report()
{
cout << "It's been an excellent week for business.\n"
<< "Sales are up 120%. Expenses are down 35%. \n";
}
void comfort()
{
cout << "Your employees think you are the finest CEO\n"
<< "in the industry. The board of directors think\n"
<< "you are the finest CEO in the industry.\n";
}
6.11 了解枚举类型enum
//enum.cpp -- using enum
#include"stdafx.h"
#include <iostream>
enum {red, orange, yellow, green, blue, violet, indigo};
int main()
{
using namespace std;
cout << "Enter color code (0-6): ";
int code;
cin >> code;
while (code >= red && code <= indigo)
{
switch (code)
{
case red: cout << "Her lips were red.\n"; break;
case orange: cout << "Her hair was orange.\n"; break;
case yellow: cout << "her shoes were yellow.\n"; break;
case green: cout << "Her nails were green.\n"; break;
case blue: cout << "Her sweatsuit was blue.\n"; break;
case violet: cout << "Her eyes were violet.\n"; break;
case indigo: cout << "Her mood was indigo.\n"; break;
}
cout << "Enter color code (0-6): ";
cin >> code;
}
cout << "Bye\n";
return 0;
}
6.12 了解break和continue语句
//jump.cpp -- using continue and break
#include "stdafx.h"
#include <iostream>
const int ArSize = 80;
int main()
{
using namespace std;
char line[ArSize];
int spaces = 0;
cout << "Enter a line of text:\n";
cout << "Line through first period:\n";
for (int i = 0; line[i] != '0'; i++)
{
cout << line[i];
if (line[i] == '.')
break;
if(line[i] != ' ')
continue;
spaces++;
}
cout << "\n" << spaces << " spaces\n";
cout << "Done.\n";
return 0;
}
6.13 连续读取
//cinfish.cpp -- non-numeric input terminates loop
#include "stdafx.h"
#include <iostream>
const int Max = 5;
int main()
{
using namespace std;
double fish[Max];
cout << "Please enter the weights of your fish.\n";
cout << "You may enter up to " << Max << " fish <q to terminate>.\n";
cout << "fish #1: ";
int i = 0;
while (i <Max&&cin >> fish[i])
{
if (++i < Max)
cout << "fish #" << i + 1 << "; ";
}
double total = 0.0;
for (int j = 0; j < i; j++)
total += fish[j];
if (i == 0)
cout << "No fish\n";
else
cout << total / i << " = average weight of " << i << " fish\n";
cout << "Done.\n";
return 0;
}
6.14 连续读取
//cingolf.cpp -- non_numeric input skipped
#include "stdafx.h"
#include <iostream>
const int Max = 5;
int main()
{
using namespace std;
int golf[Max];
cout << "Please enter your golf scores.\n";
cout << "You must enter " << Max << " round.\n";
int i;
for (i = 0; i < Max; i++)
{
cout << "round #" << i + 1 << ": ";
while (!(cin >> golf[i]))
{
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Please enter a number: ";
}
}
double total = 0.0;
for (i = 0; i < Max; i++)
total = golf[i];
cout << total / Max << " = average score " << Max << " round\n";
return 0;
}
6.15 文件输出
//outfile.cpp -- writing to a file
#include "stdafx.h"
#include <iostream>
#include <fstream>
int main()
{
using namespace std;
char automobile[50];
int year;
double a_price;
double d_price;
ofstream outFile;
outFile.open("carinfo.txt");
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;
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;
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();
return 0;
}
6.16 文件读取
//sumafile.cpp -- function with an array argument
//要运行该程序必须创建一个包含数字的文本文件,如文件名为scores.txt,包含内容如下:
//18 19 18.5 13.5 14
//16 19.5 20 18 12 18.5
//17.5
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <cstdlib>
const int SIZE = 60;
int main()
{
using namespace std;
char filename[SIZE];
ifstream inFile;
cout << "Enter name of data file: ";
cin.getline(filename, SIZE);
inFile.open(filename);
if (!inFile.is_open())
{
cout << "Could not open the file " << filename << endl;
cout << "Program terminating.\n";
exit(EXIT_FAILURE);
}
double value;
double sum = 0.0;
int count = 0;
inFile >> value;
while (inFile.good())
{
++count;
sum += value;
inFile >> 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();
return 0;
}
课后编程习题答案
//question.cpp 第六章课后编程习题答案 运行时把其余注释即可
#include "stdafx.h"
#include <iostream>
#include <cctype>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
struct bop
{
char fullname[20];
char title[20];
char bopname[20];
int preference;
};
struct charity
{
string name;
double money;
};
//question1
int main()
{
using namespace std;
char ch; cin.get(ch);
while (ch != '@')
{
if (isdigit(ch)) cin.get(ch);
else
{
if (islower(ch))
ch = toupper(ch);
else
ch = tolower(ch);
cout << ch;
cin.get(ch);
}
}
return 0;
}
//question2
int main()
{
using namespace std;
double sum = 0, average = 0;
double num[10];
int i = 0, total = 0;
double temp;
while (cin >> temp && i < 10 && !isdigit(temp))
{
num[i] = temp;
sum += num[i]; ++i;
}
if (i != 0)
average = sum / i;
for (int j = 0; j < i; ++j)
if (num[j] > average)
++total;
cout << "The average is " << average << endl;
cout << "And there are " << total << " numbers bigger than average.\n";
return 0;
}
//question3
int main()
{
using namespace std;
cout << "Please enter one of the following choices:\n"
<< "c)carnivore p)pianist\n"
<< "t)tree g)game\n";
cout << "Please enter a c, p, t, or g: ";
char ch;
cin >> 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 maple is a carnivore.\n"; break;
case 'p': cout << "A maple is a pianist.\n"; break;
case 't': cout << "A maple is a tree.\n"; break;
case 'g':
cout << "A maple is a game.\n";
}
return 0;
}
//question4
int main() {
using namespace std;
cout << "Benevolent Order of Programmers Report\n"
<< "a. display by name b. display by title\n"
<< "c. display by bopname d. diplay by preference\n"
<< "q. quit\n"; char ch;
bop member[5] = {
{ "Wimp Macho","English Teacher","DEMON",0 },
{ "Raki Rhodes","Junior Programmer","BOOM",1 },
{ "Celia Laiter","Super Star","MIPS",2 },
{ "Hoppy Hipman","Analyst Trainee","WATEE",1 },
{ "Pat Hand","Police","LOOPY",2 }
};
cout << "Enter your choice:";
while (cin >> ch && ch != 'q')
{
switch (ch)
{
case 'a':
for (int i = 0; i < 5; i++)
cout << member[i].fullname << endl;
break;
case 'b':
for (int i = 0; i < 5; i++)
cout << member[i].title << endl;
break;
case 'c':
for (int i = 0; i < 5; i++)
cout << member[i].bopname << endl;
break;
case 'd':
for (int i = 0; i < 5; i++)
{
if (member[i].preference == 0)
cout << member[i].fullname << endl;
else if (member[i].preference == 1)
cout << member[i].title << endl;
else if (member[i].preference == 2)
cout << member[i].bopname << endl;
}
break;
}
cout << "Next choice: ";
}
cout << "Bye!\n";
return 0;
}
//question5
int main() {
using namespace std;
double income, tax;
cout << "Please enter your income: ";
while (cin >> income && income >= 0)
{
if (income <= 5000)
tax = 0;
else if (income <= 15000)
tax = 0.1*(income - 5000);
else if (income <= 35000)
tax = 10000 * 0.1 + 0.15*(income - 15000);
else
tax = 10000 * 0.1 + 0.15 * 20000 + 0.2*(income - 35000);
cout << "Your tax is: " << tax << endl;
cout << "Please enter your income: ";
}
cout << "Bye!\n";
return 0;
}
//question6
int main()
{
using namespace std;
int number;
int count = 0;
cout << "Please enter the number of donator: ";
cin >> number; charity *pt = new charity[number];
for (int i = 0; i < number; i++)
{
cout << "Please enter your name: ";
cin.get();
getline(cin, pt[i].name);
cout << "Please enter the money you are going to donate: ";
cin >> pt[i].money;
if (pt[i].money > 10000) count++;
}
if (count == 0)
cout << "None(money > 10000)";
else
{
cout << "Grand Patron\n";
for (int i = 0; i < number; i++)
{
if (pt[i].money > 10000)
cout << pt[i].name << " " << pt[i].money << endl;
}
}
cout << endl;
if (10 - count == 0)
cout << "None(money < 10000)";
else {
cout << "Patron\n";
for (int i = 0; i < number; i++)
{
if (pt[i].money < 10000)
cout << pt[i].name << " " << pt[i].money << endl;
}
}
return 0;
}
//question7
int main()
{
using namespace std;
int vowel = 0, consonant = 0, other = 0;
char word[15];
cout << "Enter words (q to quit):\n";
while (cin >> word)
{
if (isalpha(word[0]))
{
if (word[0] == 'q'&&strlen(word) == 1)
break;
else if (word[0] == 'a' || word[0] == 'i' || word[0] == 'u' || word[0] == 'e' || word[0] == 'o')
++vowel;
else
++consonant;
}
else
++other;
}
cout << vowel << " words beginning with vowels\n";
cout << consonant << " words beginning with consonants\n";
cout << other << " others\n";
return 0;
}
//question8
int main()
{
char filename[20];
ifstream infile;
cout << "Enter name of data file: ";
cin.getline(filename, 20);
infile.open(filename);
if (!infile.is_open())
{
cout << "Could not open the file " << filename << endl;
cout << "Program terminating.\n";
exit(EXIT_FAILURE);
}
char a;
int count = 0;
infile >> a;
while (infile.good())
{
++count;
infile >> a;
}
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 << "The text contains " << count << " character(s)" << endl;
infile.close();
return 0;
}
//question9
int main()
{
string filename;
ifstream infile;
cout << "Enter name of data file: ";
getline(cin, filename);
infile.open(filename);
if (!infile.is_open())
{
cout << "Could not open the file " << filename << endl;
cout << "Program terminating.\n";
exit(EXIT_FAILURE);
}
int number, count = 0; infile >> number;
charity *pt = new charity[number];
for (int i = 0; i < number; i++)
{
infile.get();
getline(infile, pt[i].name);
infile >> pt[i].money;
if (pt[i].money > 10000)
count++;
}
if (count == 0)
cout << "None(money > 10000)";
else
{
cout << "Grand Patron:\n";
for (int i = 0; i < number; i++)
{
if (pt[i].money > 10000) cout << pt[i].name << " " << pt[i].money << endl;
}
}
if (10 - count == 0)
cout << "None(money < 10000)";
else
{
cout << "Patron:\n";
for (int i = 0; i < number; i++)
{
if (pt[i].money < 10000)
cout << pt[i].name << " " << pt[i].money << endl;
}
}
delete[] pt;
return 0;
}