《C++ Primer Plus》学习笔记 第6章 分支语句和逻辑运算符

在对“C ++ Primer Plus”的学习过程中尽可能详细地整理一些知识点,方便自己的学习。目前阶段的c ++内容与c语言还没有太明显的区别,整理主要是为了强化自己的编程能力,在后面学习类,对象等C ++特色内容的时候会更加细致一些。

第六章分支语句和逻辑运算符

6.3字符函数库cctype

cctype中的字符函数
函数名称 返回值

 字符isalnum()

如果参数是字母或数字,返回true
 因而isalpha() 字母,返回true
 iscntrl判断() 控制字符,返回true
 ISDIGIT() 数字(0~9),返回true
 isgraph()

除空格外的打印字符,返回true

 islower判断()

小写字母,返回true

 isprint判断()

打印字符(含空格),返回true

 ispunct判断() 标点符号,返回true
 isspace为() 标准空白字符,如空格,进纸,换行符,回车,水平制表符或垂直制表符,返回true
 isupper() 大写字母,返回true
 isxdigit判断() 十六进制数字,即0~9,a~f或A~F,返回true
 降低() 如果参数是大写字符,则返回其小写,否则返回该参数
 TOUPPER()

如果参数是小写字符,则返回其大写,否则返回该参数

6.4?:运算符(条件运算符)

也叫三目运算符:表达式表达式2:表达式

若表达1为真,则表示整个表达式的值为expression2的值,否则为expression3的值

条件运算符适用于简单关系,复杂情况用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) ? !i ? x[i] : y : x[1]);
}

将输出:Jason Quillstone为您服务。

6.5切换语句

switch(integer - expression){ 
    case label1; statement(s)
    case label1; statement(s)
    case label1; statement(s)
    ...... 
    default :statement(s)
}

其中integer - 表必须为结果为整数值常量的表达式(包括char),也可以是枚举量,switch不能处理浮点测试。若涉及取值范围,浮点测试或两个变量比较时应采用if else语句。

若整数 - 表达式没有相同的标签,则程序跳到默认一行。

若标签语句后没有休息,则会继续执行后面的所有语句。

6.5.1将枚举量作为标签

使用enum定义一组相关常量作为枚举量。通常cin无法识别枚举类型,通过输入整数来选择switch将int值和枚举量进行比较时,将枚举量提升为int。

while的循环测试中也会将枚举量提升为int类型。

代码6.11 enum.cpp

#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 << "red.\n"; break;
		case orange:cout << "orange.\n"; break;
		case yellow:cout << "yellow.\n"; break;
		case green:cout << "green.\n"; break;
		case blue:cout << "blue.\n"; break;
		case violet:cout << "violet.\n"; break;
		case indigo:cout << "indigo.\n"; break;
		//default:cout << "wrong.\n";  有while卡范围,此处没有加default语句的必要
		}
		cout << "Enter color code (0~6): ";
		cin >> code;
	}
	cout << "Bye\n";
	return 0;
}

6.6 break和continue语句

break:使程序跳到switch或循环后面的语句处执行。

继续:跳过循环体中余下代码,进行新一轮循环。继续先跳到循环的更新表达式,再到测试表达式。及语句要注意继续之后的更新表达式都会被跳过。

当继续之后有多条语句时,将比如果语句可读性更高。

goto语句介绍:

char ch;
cin >> ch;
if (ch == 'p')
	goto paris;
......
prais: statement(s);

但有人认为使用 goto 语句不好,应使用结构化控制语句 (如 if else、switch、 continue 等)来控制程序的流程。

6.7 读取数字的循环

在有些执行环境中,为了让窗口打开以便能看到输出,需要加额外的代码。对于需要输入特定字符结束程序的代码:

if (!cin) {
		cin.clear;
		cin.get();
	}
	cin.get();
	cin.get();

当用户输入错数据时,程序必须先重置 cin ,然后才能删除错误输入。

while (!(cin >> golf[i])) {
		cin.clear();//reset input
		while (cin.get() != '\n')
			continue;//get rid of bad input
		cout << "Please enter a number: ";
	}

程序在第二个 while 循环中采用 cin.get() 来读取行尾之前的所有输入,从而删除这一行的错误输入。

6.8 简单文件的输入、输出

6.8.1 文本 I/O 和文本文件

1.使用 cin 进行输入时,程序将输入视为一系列的字节,其中每个字节被解释为字符编码(二级制)。输入一开始都是字符数据即文本数据,之后 cin 对象负责把文本转化为其他类型。

2.对于输出,情况相反。整数倍转换为数字字符序列,浮点数倍转换为数字字符序列和其他字符组成的字符序列(如 253.58或-1.56E+16)。字符数据不需要转换。         输入一开始是文本文件,每个字节都储存了一个字符编码。其可能包含文本信息,也可能包含用于描述格式、字体、打印机等非文本数据。不同的是数据库和电子表格以数值格式(二进制或浮点)来储存数值数据。

通过文本编译器创建文本文件。DOS中的EDIT、 Windows 中的“记事本”、 Unix/Linux 中的 vi 或 emacs 。IDE中的源代码编译器生成的也是文本文件。

6.8.2 写入到文本文件中

1.必须包含头文件 fstream

2.头文件 fstream 定义了一个用于处理输出的 ofstream 类

3.需要声明一个或多个 ofstream 变量(对象),并命名。

4.必须将 ofstream 对象与文件关联起来,方法之一是用 open() 

5.使用完文件后,用方法 close() 将其关闭

6.可结合使用 ofstream 对象和运算符 << 来输出各种类型的数据

声明 ofstream 对象:

ofstream outFile;
ofstream fout;

将这种对象与文件关联

outFile.open("fish.txt");
char filename[50];
cin>>filename;
fout.open(filename);

方法 open() 接受一个 C+ 风格字符串作为参数,这可以是一个字面字符串,也可以是存储在数组中的字符串。

(open()到底怎么用?难道不是提取文件吗?怎么又字符串了)

如何使用这种对象:

double wt =125.8;
outFile << wt;
char line[81] = "Obhects are closer than they appear";
fout << line << endl;

声明一个 ofstream 对象并将它与文件关联起来后,便可以像用 cout 那样使用它。

步骤:

1.包含头文件 fstream 

2.创建一个 ofstream 对象

3.将该 ofstream  对象与文件关联起来

4. 像用 cout 那样使用它

代码6.15 输出文件:

#include<iostream>
#include<fstream>
using namespace std;

int main() {
	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;

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

程序运行后, outFile 将 cout 显示在屏幕上的内容写入到程序可执行文件所在目录的名为 carinfo.txt 的文本文件中。

格式化方法:

cout<<fixed  //用一般的方式输出浮点型,例如C++程序在控制台显示的时候大一点的数,显示的时候使用了科学计数法,使用该命令即可像一般的方式显示

cout.precision(2) //设置精确度为2,并返回上一次的设置。

cout.setf(iOS_base::showpoint)  //显示浮点数小数点后面的零。

可参考这条博文:https://blog.csdn.net/u011321546/article/details/9293547 感谢大佬分享

6.8.3读取文本文件

1.必须包含头文件 fstream

2.头文件 fstream 定义了一个用于处理输出的 ifstream 类

3.需要声明一个或多个 ifstream 变量(对象),并命名。

4.必须将 ifstream 对象与文件关联起来,方法之一是用 open() 

5.使用完文件后,用方法 close() 将其关闭

6.可结合使用 ifstream 对象和运算符 >> 来输出各种类型的数据

7.可以使用 ifstream 对象和 get() 方法来读取一个字符,使用 ifstream 对象和 getline() 方法来读取一行字符。

8.可结合使用 ifstream 和 eof() 、fail() 等方法来判断输入是否成功。

9.ifstream 对象本身被作为测试条件时,如果最后一个读取操作成功,它将被转换成布尔值 true, 否则被转换成 false 。

声明 iftream 对象

ifstream inFile;
ifstream fin;

将这种对象与文件关联起来

inFile.open("bowling.txt");
char filename[50];
cin >> filename;
fin.open(filename);

方法 open() 接受一个 C+ 风格字符串作为参数,这可以是一个字面字符串,也可以是存储在数组中的字符串。

如何使用:

double wt;
inFile >> wt;
char line[81];
fin.getline(line, 81);

声明一个 ofstream 对象并将它与文件关联起来后,便可以像用 cin 那样使用它。

试图打开一个不存在的文件会导致后面使用 ifstream 对象进行输入时失败。检查文件是否被成功打开的方法是 is_open()

inFile.open("bowling.txt");
if ( !inFile.is_open )
    exit(EXIT_FAILURE);

成功打开 is_open() 将返回 true 。函数 exit() 的原型实在头文件 cstdlib 中定义的,在该头文件中还定义了一个用于同操作系统通信的参数值EXIT_FAILURE ,函数 exit() 将终止程序。

代码 6.16 读取文件:

#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凭借该字符变量去读取文件数据
	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;
	}// while input good and not a EOF
	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;
}

要在程序的可执行文件夹中创建一个文本文档,作为输入文件。或者再输入的文件名中包含路径。

为保证读取文件顺利进行:

1.程序读取文件不能超过EOF。若最后一次读取数据遇到EOF,方法 eof() 将返回 true 。

2.若最后一次读取发生了类型不匹配,方法 fail() 将返回 true (若遇到EOF, 该方法也将返回 true )。

3.若最后一次读取发生了文件受损或硬件故障,方法 bad() 将返回 true 。

4.更简单的方法是,不用分别判断以上三点,当没有发生任何错误时,方法 good() 返回 true 。

while (inFile.good()) {
		......
	}// while input good and not a EOF

也可用上面三点判断循环终止的真正原因:

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";

这些代码紧跟在循环后面。 由于 eof() 只能判断是否到达EOF,而 fail() 可用于检查EOF 和类型不匹配,因此先判断是否到达 EOF。如果执行到了 else if  则可排除 EOF,若  fail() 返回  true ,便可断定循环终止原因是类型不匹配。

方法good()指出最后一次读取输入的操作是否成功,故用在执行读取后立刻进行测试。

测试代码1:

inFile >> value;
while (inFile.good()) {
	......
	inFile >> value;
}

因为,表达式inFile >> value的结果为inFile,但是在需要一个bool值的情况下,inFile的值为inFile.good(),即true或false。

测试代码2(精简):

while (inFile >> value) {
    ......
}

猜你喜欢

转载自blog.csdn.net/Perce_Issac/article/details/81705172
今日推荐