C++ Primer 学习笔记(第五章)

来源:互联网 发布:什么软件可以做一寸照 编辑:程序博客网 时间:2024/06/06 04:16

第五章 语句

5.1 简单语句

1.空语句

【 ; 】分号    单独一个分号代表一个空语句

    ;    //空语句     int s, a = 0;    while (cin >> s&&s != a)        ;     //空语句

2.块

块是指用花括号括起来的部分,他又被称作作用域:

    {}     // 块 作用域

5.2 语句作用域

5.3 条件语句

1.if语句

if需要注意括号的范围,尤其是在if-else语句中,else的范围添加错误就很容易出现程序继续向下运行的情况,因此需要养成范围内必须使用花括号的习惯。

if()

{     }

else

{     }

 

2.switch规范

switch语句要求每一个case内都必须加一个‘break’,最后一个case后要加default。

如果没有加break,在满足上边的case后,会运行下边的程序。

default内可以不添加任何程序,但是一定要写上(良好的编程习惯)。

例程:统计一串数字中aeiou的数量

void run2(){unsigned aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0,otherCnt=0;cout << "请输入一串字符,并分别统计aeiou字符的数量" << endl;char ch;while(cin>>ch){switch (ch) {case 'a':++aCnt;break;case 'e':++eCnt;break;case 'i':++iCnt;break;case 'o':++oCnt;break;case 'u':++uCnt;break;default:++otherCnt;break;}}cout << "Number of vowel a :" << aCnt << endl;cout << "Number of vowel e :" << eCnt << endl;cout << "Number of vowel i :" << iCnt << endl;cout << "Number of vowel o :" << oCnt << endl;cout << "Number of vowel u :" << uCnt << endl;cout << "Number of vowel otherwords :" << otherCnt << endl;}

例程:统计元音字母的数量

void run3(){cout << "请输入一串字符,并自动统计元音字符的数量" << endl;unsigned aCnt=0,otherCnt=0;char ch;while (cin >> ch) {switch (ch) {case 'a':case 'e':case 'i':case 'o':case 'u':++aCnt;break;default:++otherCnt;break;}}cout << "Number of vowel 元音 :" << aCnt << endl;cout << "Number of vowel otherwords :" << otherCnt << endl;}

5.4 迭代语句

1.while循环

迭代语句通常被称之为循环,目前的迭代用的普遍的有四种。

while语句用法:

while() {}

①当不确定要循环多少次时用while比较合适;

②再循环结束后想控制变量一般用while;

 

2.传统for语句

for( ; ; ) {}

中间的内容可以不写,但是分号必须有,可以通过break进行打断。

 

3.范围for语句

C++11引入了一种新的for语句,新语句的用法是:

    for(declaration:expression)

          statement

①declaration定义一个变量,并且declaration可以转化为expression中的任意类型。因此declaration一般都会采用auto型。

②expression表示的是一个序列,通常是使用vector和string等表达形式。

③statement是循环执行的内容。

例程:将序列中的都乘2并输出

   vector<int> v = {0,1,2,3,4,5,6,7,8,9 };    for (auto &r : v)    {        r*= 2;        cout<< r << endl;    } 

4.do while语句

该语句的特点是无论条件值如何,都会执行一次循环。

    do

        statement

        while (condition);

 

5.5 跳转语句

跳转语句一共有四种:break、continue、goto、return。

1.break语句

break语句可用于while、do while、for和switch中。

它可以直接终止该循环。

 

2.contimue语句

continue可以用于while、do while和for中。

它可以终止本次循环,contine后的程序不在执行,直接进行下一次迭代。

 

3.goto语句

goto语句的作用是从goto语句无条件跳转到统一函数内的另一条语句。

不要在程序中使用goto语句,因为它使得程序难理解同时很难修改。

 

4.return

不经常再循环中使用,经常在函数中使用,详情请看6.3节。

 

5.6 try语句块和异常处理

1.throw表达式

2.try表达式

3.标准异常

//没太搞明白异常部分,有时间回头看看吧

原创粉丝点击