分支语句和逻辑运算符
6.1、if语句
- if
结构
例子
统计输入的字符数、空格数
// if.cpp -- using the if statement
#include <iostream>
int main()
{
using std::cin; // using declarations
using std::cout;
char ch;
int spaces = 0;
int total = 0;
cin.get(ch);
while (ch != '.') // quit at end of sentence
{
if (ch == ' ') // check if ch is a space
++spaces;
++total; // done every time
cin.get(ch);
}
cout << spaces << " spaces, " << total;
cout << " characters total in sentence\n";
// cin.get();
// cin.get();
return 0;
}
- if else
// ifelse.cpp -- using the if else statement
#include <iostream>
int main() {
char ch;
std::cout << "Type, and I shall repeat.\n";
std::cin.get(ch);
while (ch != '.') {
if (ch == '\n')
std::cout << ch; // done if newline
else
std::cout << ++ch; // done otherwise
std::cin.get(ch);
}
// try ch + 1 instead of ++ch for interesting effect
std::cout << "\nPlease excuse the slight confusion.\n";
// std::cin.get();
// std::cin.get();
return 0;
}
/*
Type, and I shall repeat.
An ineffable joy suffused me as I beheld
Bo!jofggbcmf!kpz!tvggvtfe!nf!bt!J!cfifme
the wonders of modern computing
uif!xpoefst!pg!npefso!dpnqvujoh
*/
- if else if 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);
// cin.get();
// cin.get();
return 0;
}
/*
Enter a number in the range 1-100 to find my favorite number: 50
Too high -- guess again: 25
Too low -- guess again: 31
Too high -- guess again: 28
Too high -- guess again: 27
27 is right!
*/
最好不要把variablevalue写成了valuevariable
6.2、逻辑表达式
- or
// or.cpp -- using the logical OR operator
#include <iostream>
int main() {
using namespace std;
cout << "This program may reformat your hard disk\n"
"and destroy all your data.\n"
"Do you wish to continue? <y/n> ";
char ch;
cin >> ch;
if (ch == 'y' || ch == 'Y') // y or Y
cout << "You were warned!\a\a\n";
else if (ch == 'n' || ch == 'N') // n or N
cout << "A wise choice ... bye\n";
else
cout << "That wasn't a y or n! Apparently you "
"can't follow\ninstructions, so "
"I'll trash your disk anyway.\a\a\a\n";
// cin.get();
// cin.get();
return 0;
}
- &&
// and.cpp -- using the logical AND operator
#include <iostream>
const int ArSize = 6;
int main() {
using namespace std;
float naaq[ArSize];
cout << "Enter the NAAQs (New Age Awareness Quotients) "
<< "of\nyour 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) { // 2 quitting criteria
naaq[i] = temp;
++i;
if (i < ArSize) { // room left in the array,
cout << "Next value: ";
cin >> temp; // so get next value
}
}
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\n"
<< "the New Age than you do.\n";
}
// cin.get();
// cin.get();
return 0;
}
/*
Enter the NAAQs (New Age Awareness Quotients) of
your neighbors. Program terminates when you make
6 entries or enter a negative value.
First value: 28
Next value: 721
Next value: 15
Next value: 6
Next value: 130
Next value: 145
Enter your NAAQ: 50
3 of your neighbors have greater awareness of
the New Age than you do.
*/
首先将第一个输入值读入到临时变量(temp)中。然后,while测试条件查看数组中是否还有空间(i<ArSize)以及输入值是否为非负(temp>0)。
for more
// more_and.cpp -- using the logical AND operator
#include <iostream>
const char *qualify[4] = { // an array of pointers*/
// to strings
"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 = 1;
else if (age >= 50 && age < 65)
index = 2;
else
index = 3;
cout << "You qualify for the " << qualify[index];
// cin.get();
// cin.get();
return 0;
}
/*
Enter your age in years: 33
You qualify for the 10,000-meter race.
*/
- not
if(!(x>5)) //if(x<=5)
例子
// not.cpp -- using the not operator
#include <iostream>
#include <climits>
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";
// cin.get();
// cin.get();
return 0;
}
bool is_int(double x) {
if (x <= INT_MAX && x >= INT_MIN) // use climits values
return true;
else
return false;
}
/*
Yo, dude! Enter an integer value: 234567890345678
Out of range -- please try again: 1234567890
You've entered the integer 1234567890
Bye
*/
如果给读取int值的程序输入一个过大的值,很多C++实现只是将这个值截断为合适的大小,不会通知丢失了数据。因此首先将可能得int值作为double值来读取。double类型的精度足以存储典型的int值,且取值范围更大。 另一种选择是,使用long long来存储输入的值,因为其取值范围比int大。
- 逻辑运算符与优先级
x>5 && x<10
//被解释为
(x>5)&&(x<10)
另外一个例子
!(x>5) //is it false that x is greater than 5
!x>5 //is !x greater than 5
6.3、字符函数库cctype
简化诸如确定字符是否是大写字母、数字、标点符号等工作。
例如,如果ch是一个字母,则isalpha(ch)函数返回一个非零值,否则返回0.
同样,如果ch是标点符号(逗号或句号),函数ispunct(ch)将返回true。(这些函数的返回类型为int,而不是bool,但通常bool转换能让我们将它视为bool类型。)
例子
使用isalpha()来检查字符是否为字母字符,
使用isdigit()来测试字符是否为数字字符。
使用isspace()来测试字符是否为空白,如换行符、空格和制表符。
使用ispunct()来测试字符是否为标点符号。
// 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;
}
/*
Enter text for analysis, and type @ to terminate input.
wsteqdtfgyipo1245836782,..
125r6t38ehwcv fwefjhcdy 89u2n fcxt76 revf
ty8uijtyhjn wegyh3782..,,yugh@
58 letters, 11 whitespace, 26 digits, 7 punctuations, 0 others.
*/
cctype字符函数
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-k0ZUiJ7n-1692104290283)(.\pics\0815-2.png)]
6.4、? :运算符
例子
// condit.cpp -- using the conditional operator
#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;
// cin.get();
// cin.get();
return 0;
}
/*
Enter two integers: 14 78
The larger of 14 and 78 is 78
*/
与if else序列相比,条件运算符更佳简洁。可以将条件表达式嵌套在另一个条件表达式。
const char x[2][20]={"Jason", "at your service\n"};
const char*y="Quillstone";
for(int i=0;i<3;i++){
cout<<((i<2)? !x?x[i]:y :x[i]);
}
6.5、switch语句
switch语句的通用格式:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ROHHpW6H-1692104290284)(.\pics\0815-3.png)]
// switch.cpp -- using the switch statement
#include <iostream>
using namespace std;
void showmenu(); // function prototypes
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";
// cin.get();
// cin.get();
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";
}
也可以使用字符
- 将枚举量用作标签
// enum.cpp -- using enum
#include <iostream>
// create named constants for 0 - 6
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";
// cin.get();
// cin.get();
return 0;
}
/*
Enter color code (0-6): 1
Her hair was orange.
Enter color code (0-6): 2
Her shoes were yellow.
Enter color code (0-6): 3
Her nails were green.
Enter color code (0-6): 4
Her sweatsuit was blue.
Enter color code (0-6): 0
Her lips were red.
Enter color code (0-6): 6
Her mood was indigo.
Enter color code (0-6): 8
Bye
*/
- switch和if else
switch语句和if else语句都允许程序从选项中选择。相比之下,if else更通用。例如,它可以处理取值范围。
然而,switch并不是为处理取值范围而设计的。switch语句中的每一个case标签都必须是一个单独的值。另外,这个值必须是整数(包括char),但是Switch无法处理浮点数。
6.6、break和continue
continue结构
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LYITXGL4-1692104290285)(.\pics\0815-5.png)]
break结构
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-P6T9NBeW-1692104290285)(.\pics\0815-6.png)]
例子
// jump.cpp -- using continue and break
#include <iostream>
const int ArSize = 80;
int main() {
using namespace std;
char line[ArSize];
int spaces = 0;
cout << "Enter a line of text:\n";
cin.get(line, ArSize);
cout << "Complete line:\n" << line << endl;
cout << "Line through first period:\n";
for (int i = 0; line[i] != '\0'; i++) {
cout << line[i]; // display character
if (line[i] == '.') // quit if it's a period
break;
if (line[i] != ' ') // skip rest of loop
continue;
spaces++;
}
cout << "\n" << spaces << " spaces\n";
cout << "Done.\n";
// cin.get();
// cin.get();
return 0;
}
/*
Enter a line of text:
Let's do lunch today.You can pay!
Complete line:
Let's do lunch today.You can pay!
Line through first period:
Let's do lunch today.
3 spaces
Done.
*/
在C++中,也有goto语句。下面的语句将跳转paris:作为标签的位置:
char ch;
cin>>ch;
if(ch=='P')
goto paris;
cout<...
....
paris:cout<<"You arriced at here.\n";
在大多数情况下,使用goto语句不好。尽可能不用goto语句去控制程序的流程。
6.7、读取数字的循环
例子
// cinfish.cpp -- non-numeric input terminates loop
#include <iostream>
const int Max = 5;
int main() {
using namespace std;
// get data
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 << ": ";
}
// calculate average
double total = 0.0;
for (int j = 0; j < i; j++)
total += fish[j];
// report results
if (i == 0)
cout << "No fish\n";
else
cout << total / i << " = average weight of "
<< i << " fish\n";
cout << "Done.\n";
// code to keep VC execution window open if q is entered
// if (!cin) // input terminated by non-numeric response
// {
// cin.clear(); // reset input
// cin.get(); // read q
// }
// cin.get(); // read end of line after last input
// cin.get(); // wait for user to press <Enter>
return 0;
}
/*
Please enter the weights of your fish.
You may enter up to 5 fish <q to terminate>.
fish #1: 3
fish #2: 2
fish #3: 3
fish #4: 1
fish #5: 4
2.6 = average weight of 5 fish
Done.
*/
为了让窗口打开以便能够看到输出,需要添加额外的代码。
// code to keep VC execution window open if q is entered
if (!cin) // input terminated by non-numeric response
{
cin.clear(); // reset input
cin.get(); // read q
}
cin.get(); // read end of line after last input
cin.get(); // wait for user to press <Enter>
例子2
使用cin输入得分。如果检测输入的不是数字,则拒绝,并要求用户继续输入数字。可以看到,可以使用cin输入表达式来检测输入是不是数字。程序发现用户输入错误内容时,应该采取3个步骤:
- 重置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;
for (i = 0; i < Max; i++) {
cout << "round #" << i + 1 << ": ";
while (!(cin >> golf[i])) {
cin.clear(); // reset input
while (cin.get() != '\n')
continue; // get rid of bad input
cout << "Please enter a 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";
// cin.get();
// cin.get();
return 0;
}
/*
Please enter your golf scores.
You must enter 5 rounds.
round #1: 12
round #2: 23
round #3: 23
round #4: ysdiwvf
Please enter a number: 2341
round #5: 23
484.4 = average score 5 rounds
*/
在程序中,错误处理代码的关键部分如下:
while (!(cin >> golf[i])) {
cin.clear(); // reset input
while (cin.get() != '\n')
continue; // get rid of bad input
cout << "Please enter a number: ";
}
如果用户输入88,则cin表达式为true,因此将一个值放到数组中;而表达式!(cin>>golf[i])为false,因此结束内部循环。
如果用户输入ysyv,则cin表达式为false,因此不会将任何值放到数组中,而表达式!(cin>>golf[i])为true,因此进入内部的while循环。
循环的是先用clear()方法重置输入,如果省略该句,程序将拒绝继续读取输入。接下来,程序在while循环中使用cin.get()来读取行尾之前的所有输入,从而删除这一行的错误输入。另一种方法是读取到下一个空白字符,这样每次删除一个单词,而不是一整行。最后,程序高速用户,需要 输入一个数字。
6.8、简单文件输入/输出
- 文本IO和文本文件
char ch;
cin>>ch;
//输入整数
int n;
cin>>n;
//输入double
double x;
cin>>x;
//char数组
char word[50];
cin>>word;
cin.getline(word,50);
- 写入到文本文件中
ofstream outFile;
ofstream fout;
//打开文件的两种方式
outFile.open("fish.txt");
char filename[50];
cin>>filename;
fout.open(filename);
//写入数据
double wt=1255.8;
outFile<<wt; //写入一个数据
char line[87]="Objects are closer than they appear.";
fout<<line<<endl; //写入一行数据
使用文件输出的主要步骤。
- 包含一个头文件fstream
- 创建一个ofstream对象
- 将该ofstream对象同一个文件关联起来
- 像使用cout那样使用ofstream对象
例子
要求用户输入信息,然后将信息显示到屏幕上,再将这些信息写入到文件中。
// 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;
}
/*
Enter the make and model of automobile: Filly Perky
Enter the model year: 2008
Enter the original asking price: 13500
Make and model: Filly Perky
Year: 2008
Was asking $13500.00
Now asking $12325.50
*/
打开文件和关闭文件
ofstream outFile; // create object for output
//文件不存在将创建文件;文件存在则清空文件内容
outFile.open("carinfo.txt"); // associate with a file
.....
outFile.close(); // done with file
- 读取文本文件
//1、创建对象
ifstream inFile;
ifstream fin;
//2、对象和文件关联
inFile.open("bowling.txt"); //way1
char filename[50]; //way2
cin>>filename;
fin.open(filename);
//3、使用对象
double wt;
inFile>>wt; //read a number from txt
char line[81];
fin.getline(line,81); //read a line of text
检查文件是否被成功打开
inFile.open("bowling.txt");
if(!inFile.is_open()){
exit(EXIT_FAILURE);
}
例子
打开用户指定的文件,读取其中的数字,然后指出文件中包含多少个值以及它们的和与平均值
// 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;
}
ed 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;
}