学习笔记:C++ primer Plus chap5

C++ primer Plus chap5

目录

5.1 for 循环

5.1.1 for循环的组成部分

5.1.2 回到for循环

5.1.3 修改步长

5.1.4 使用for循环访问字符串

5.1.5 递增运算符(++)和递减运算符(--)

5.1.6 副作用和顺序点

5.1.7 前缀格式和后缀格式

5.1.8 递增递减运算符和指针

5.1.9 组合赋值运算符

5.1.10 复合语句(语句块)

5.1.11 其它语法技巧——逗号运算符

5.1.12 关系表达式

5.1.13 赋值、比较和可能犯的错误

5.1.14 C-风格字符串比较

5.1.15 比较string类字符串

5.2 while循环

5.2.1 for与while

5.2.2 等待一段时间:编写延时循环

5.3 do while循环

5.4 基于范围的for循环(C++11)

5.5 循环和文本输入

5.5.1 使用cin进行输入

5.5.2 使用cin.get(char)进行补救

5.5.3 使用哪一个cin.get()

5.5.4 文件尾条件

5.5.5 另一个cin.get()版本

5.6 嵌套循环和二维数组

5.6.1 初始化二维数组

5.6.2 使用二维数组

 

 

 

 

 

第一部分

  1. for 循环

for的组成部分完成下面这些步骤:

(1)设置初始值。

(2)执行测试,看看循环是否应当继续进行。

(3)执行循环操作。

(4)更新用于测试的值。

初始化、测试和更新操作构成了控制部分。这些操作由小括号括起,其中每部分都是一个表达式,彼此由分号隔开。for 循环是入口条件循环--先判断bool值为true or false。

C++ 常用的方式是,在for和括号之间加上一个空格,而省略号函数名与括号之间的空格。

这样从视觉上强化了控制语句和函数调用之间的区别。

控制部分后面的部分叫做循环体,只要测试表达式为true,便被执行。常见的做法是缩进for语句体,使它看上去比较显著。

for (initialization;test-expression;update-expression) //控制部分

body //循环体

int i ;

for (i=0;i<5;i++)

cout<<"C++ knows loops.\n";

cout<<"C++ knows when to stop.\n";

输出五次 C++ knows loops.

C++语法将整个for看做一条语句。

二、表达式和语句

  1. 表达式和语句

    任何值或任何有效的值和运算符的组合都是表达式。

    C++将赋值表达式的值定义为左侧成员的值。

    <<运算符的优先级比表达式中使用的运算符高。//程序express.cpp。cout.setf()函数。

    age = 100 //表达式

    age = 100 ; //语句

  2. 非表达式和语句

    表达式加分号可以成为语句,但反过来就不对了。返回语句、声明语句和for循环就不可以。

  3. 修改规则

    for (int i=0;i<5;i++) //i=0是表达式。int i=0;是语句。

    可以在for循环的初始化部分中声明变量。

    刚才的代码被注释掉部分显示i只在循环中可用。

 

 

学习笔记:C++ primer Plus chap5_第1张图片

学习笔记:C++ primer Plus chap5_第2张图片

此处,步长值为1。可以修改,修改表达式3就可以了。如i+=2

提一下a++和++b。

a++意味着使用a的当前值计算表达式。++b先将b加1,使用新的值计算表达式。

三、使用for循环访问字符串

//程序forstr1.cpp

//forstr1.cpp--using for with a string
#include
#include
int main()
{
	using namespace std;
	
	cout << "Enter a word: ";
	string word;
	cin >> word;

	//display letters in reverse order
	for (int i = word.size() - 1;i >= 0;i--)
		cout << word[i];
	cout << "\nBey.\n";
	/*1
        int guest = 1;
	while (guest++ < 10)
		cout << guest << endl;
	for (int n = 5;n > 0;--n)
		cout << n<< endl;
	for (int n = 5;n > 0;n--)
		cout << n<< endl;*/
	/*2
        int arr[5] = { 11,12,13,14,16 };
	int *pt = arr;//pt points to arr[0],11
	cout<<++ *pt;*/
	return 0;
}


四、副作用和顺序点

1、副作用:计算表达式时对某些东西(如存储在变量中的值)进行了修改。

顺序点:程序执行过程中的一个点。如语句中分号就是一个顺序点。

Forstr1.cpp注释掉部分1

除了副作用,前缀和后缀一般没什么区别。对于用户定义的类型,如果有递减运算符,前缀格式的效率更高。

五、递增/递减运算符和指针

1、指针递增和递减遵循指针算术规则。如pt指向某个数组的第一个元素,++pt将修改pt,使之指向第二个元素。

2、注意运算符位置和优先级:

(1)前缀递增和前缀递减和解除引用运算符的优先级相同。

(2)后缀递增和后缀递减比前缀运算符的优先级高。

egs:int arr[5]={11,12,13,14,16}

int *pt = arr;//pt points to arr[0],11

++pt; //pt points to arr[1],12

 

Int x= *++pt; //先将pt加1,而后取其指向的值,x=13

++*pt; //先取pt指向的值,然后将其加1,比如现在pt指向arr[3],14,则此表达式值为15

大家算一下,假设现在pt指向arr[3],14

(*pt)++ ?         15

y=*pt++ ?        16

 Forstr1.cpp注释掉部分2

六、组合赋值运算符

学习笔记:C++ primer Plus chap5_第3张图片

 

七、复合语句(语句块)

1、还记得前面说的循环体必须是一条语句吗?如果想包含多条语句怎么办?

方法是用两个花括号来构造一条复合语句(代码块)。将被视为一条语句。

 

2、其它语法技巧

逗号:逗号运算符,将两个表达式合并为一个。逗号运算符是一个顺序点。

声明中的逗号将变量列表中相邻的名称分开。此时逗号是一个列表分隔符。

不能用逗号运算符将两个声明组合起来。

逗号运算符优先级最低,表达式的值是第二部分的值。

见forstr2.cpp

//forstr2.cpp--reversing an array
#include
#include
int main()
{
	using namespace std;
	cout << "Enter a word: ";
	string word;

	cin >> word;
	//pysically modify string object
	char temp;
	int i, j;
	for (j = 0, i = word.size()-1;j < i;--i, ++j)
	{
		temp = word[i];
		word[i] = word[j];
		word[j] = temp;

	}
	cout << word<<"\nDone\n";
	return 0;

}


3、关系表达式

 

 

 

学习笔记:C++ primer Plus chap5_第4张图片

 

注意赋值运算符和等于运算符。

关系运算符比算术运算符优先级低。

 

  1. 字符比较

    注意用引号括起的字符串常量也是其地址

    C-style

    strcmp()函数比较两个字符或字符串。stercmp(string1,string2)如果两个字符串相同,则返回值为0;若第一个在第二个之前,则返回负值;反之返回正值。见cmpster1.cpp

    使用string类字符串。类设计能够使用关系运算符比较字符串。见srecmp2.cpp

 

//compstr1.cpp--comparing strings using arrays
#include
#include
int main()
{
	using namespace std;
	char word[5] = "?ate";
	for (char ch = 'a';strcmp(word, "mate");ch++)
	{
		cout << word << endl;
		word[0] = ch;
	}
	cout << "After loop ends,word is " << word << endl;
	return 0;
}

抱歉,两个应该命名有规律的,不知道当时怎么了,这么命名的。

//strcmp2.cpp--comparing strings using arrays
#include
#include
int main()
{
using namespace std;
char word[5] = "?ate";
for (char ch = 'a';word != "mate";ch++)
{
cout << word << endl;
word[0] = ch;
}
cout << "After loop ends,word is " << word << endl;
return 0;
}

第二部分

1、While循环

还记得for循环由那几部分组成吗?

(1)设置初始值。

(2)执行测试,看看循环是否应当继续进行。

(3)执行循环操作。

(4)更新用于测试的值。

而while循环是没有初始化和更新部分的for循环,只有测试条件和循环体。

while (test-condition)

body

or

while (test-condition)

        {

body

}

执行完循环体后,返回测试条件,对它进行重新评估…直到测试条件为false为止。循环体中的代码必须影响测试条件。

while循环也是入口条件循环。

学习笔记:C++ primer Plus chap5_第5张图片

在设计循环时,请记住下面几条指导原则:

  1. 指定循环终止条件;
  2. 在首次测试之前初始化条件;
  3. 在条件被再次测试之前更新条件。

2、等待一段时间

While可完成

long wait=0;

while (wait<10000)

    wait++;

函数clock()

定义了符号常量CLOCKS_PER_SEC & CLOK_PER_SEC

该常量等于每秒钟包含的系统时间单位数。

系统时间/CLOCKS_PER_SEC= 每秒钟包含的系统时间单位数。

秒数*CLOCK_PER_SEC=以系统时间为单位的时间

程序waiting.cpp

 

//waiting.cpp--using clock() in a time-delay loop
#include
#include
int main()
{
	using namespace std;
	cout << "Enter the delay time, in seconds: ";
	float secs;
	cin >> secs;
	clock_t delay = secs*CLOCKS_PER_SEC;//CONVERT TO CLOCK TICKS
	cout << "starting\a\n";
	clock_t start = clock();
	while (clock() - start < delay)
		;
	cout << "done\a\n";
	return 0;
}

3、do while 循环

出口条件循环

do

    body

while (test-expression);

见dowhile.cpp

 

//dowhile.cpp--exit-condition loop
#include
int main()
{
	using namespace std;
	int n;

	cout << "Enter number in the range 1-10 to find ";
	cout << "my favorite number\n";
	do
	{
		cin >> n;    //execute body
	} while (n != 7);//then test
	cout << "Yes, 7 is my favorite.\n";
	return 0;
}
4、基于范围的for循环
C++11新循环:基于范围(range-based)的for 循环。
对数组(或容器类,如vector和 array)的每个元素执行相同的操作。

double prices[5] = {4.99,10.99,6.87,7.99,8.49};

for (double x_: prices)

cout<

其中,x最初表示数组price的第一个元素。显示第一个元素后,不断执行循环,而x依次表示数组的其它元素。因此,上述代码显示数组中的每个值。

需要修改数组的元素,需要使用不同的循环变量法:

for (double &x:price)

    x=x*0.80;

&表明x是一个引用变量。

 

 

第三部分:循环和文本输入

1、使用原始的cin进行输入

何时停止?可以选择哨兵字符。

textin1.cpp

//textin.cpp--reading chars with a while loop
#include
int main()
{
	using namespace std;
	char ch;
	int count = 0;   //use basic input
	cout << "Enter characters;enter #-to quit :\n";
	cin >> ch;
	cout << ch << endl;

	while (ch != '#')
	{
		cout << ch;   //echo the character
		++count;
		cin >> ch;
	}
	cout << endl << count << " characters read\n";
	return 0;
}


cin 读取char值时,与读取其它基本类型一样,将忽略空格和换行符。后面还可继续输入,是因为输入被缓冲,意味着只有用户按下回车键,输入内容才会被发送给程序。

2、使用istream 类中成员函数cin.get(char)进行补救

这个函数不会忽略空格。输入仍被缓冲。

3、简述函数重载

C++支持被称为函数重载的OOP特性。函数重载允许创建多个同名函数,条件是它们的参数列表不同。

4、文件尾条件

从文件读取数据时,可以在命令提示符模式下输入下面的命令:

Gofish

学习笔记:C++ primer Plus chap5_第6张图片

 

 

第四部分 循环嵌套和二维数组

初始化

学习笔记:C++ primer Plus chap5_第7张图片

见程序nested.cpp

 

//nested.cpp--nested loops and 2-D array
#include
#include
const int Cities=5;
const int Years = 4;//如果希望字符串是可修改的,则应省略限定符const。
int main()
{
	using namespace std;
	const char * cities[Cities] =
	{
		"Gribble City",
		"Gribbletown",
		"New Gribble",
		"San Grible",
		"Gribble Vista"
	};

	int maxtemps[Years][Cities] = //2维数组
	{
		{96,100,87,101,105},
		{96,98,91,107,104},
		{97,101,93,108,107},
		{98,103,95,109,108}
	};

	cout << "Maxmun temperatures for 2008-2011\n\n";
	for (int city = 0;city < Cities;++city)
	{
		cout << cities[city] << ":\t";
		for (int year = 0;year < Years;year++)
			cout << maxtemps[year][city] << "\t";
		cout << endl;
	}
	//cin.get();
	return 0;
}

见myblock.cpp和myblock2.cpp(后面一个例子是课后第六题要求,用到二维数组)

//myblock.cpp--exercise 5
//假设要销售《C++ for Fools》一书。请编写一个程序,输入全年中每个月的销售量(图书册数)。
//程序通过循环,使用初始化为月份字符串的char数组(或string对象数组)逐月进行提示,并将输入的数据存储在一个int数组中。
//然后,程序计算数组中各元素的总数,并报告这一年的销售情况。
#include
#include
using namespace std;
int main()
{
	
	cout << "Now let's begin to calculate the number of books we've sold" << endl;;
	string month[12] = { "January","February","March","April","May","June","July","August","Septemer","Octuber","November","December" };
	string *pt = month;
	int arr[12] = {};
	double sum = 0.0;
	cout << "Enter the number of books you've sold in \n";
	for (int i = 0;i < 12;i++)
	{
		cout<< *(pt++)<<"  ";
		cin >> arr[i];
		sum += arr[i];
	}
	cout << "We've sold " << sum << " books in last year!\n";
}

//myblock2.cpp--exercise 6
//假设要销售《C++ for Fools》一书。请编写一个程序,输入三年中每个月的销售量(图书册数)。
//程序通过循环,使用初始化为月份字符串的char数组(或string对象数组)逐年进行提示,并将输入的数据存储在一个int二维数组中。
//然后,程序计算数组中各维元素的总数,并报告这三年的销售情况。
#include
#include
using namespace std;
int main()
{

cout << "Now let's begin to calculate the number of books we've sold in last three years" << endl;
string year[3] = { "the year before last year","last year","this year" };
string month[12] = { "January","February","March","April","May","June","July","August","Septemer","Octuber","November","December" };
string *py = year;
string *pm = month;

int arr[3][12] = {};
int sum[3] = { 0,0,0};

cout << "Enter the number of books you've sold in last three years.(use the\"  \" to separat every month'sales volume)\n";
for (int i = 0;i < 3;i++)
{
	int n = 0;
	cout<< *(py++)<> arr[i][j];
		//cout << arr[i][j] << endl;
		sum[i] += arr[i][j];
	}
}
cout << "We've sold " << sum[0] << " books in " << year[0] << "\n";
cout << "We've sold " << sum[1] << " books in " << year[1] << "\n";
cout << "We've sold " << sum[2] << " books in " << year[2] << "\n";
cout << "We've sold " << sum[0]+ sum[1]+ sum[2] << " books in the last three years\n";
} 

你可能感兴趣的:(C++)