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

本章知识点:

 if、if else语句

 &&、||、!

 cctype字符函数库

 条件运算符:?:

 switch语句

 continue和break语句

 读取数字的循环

 基本文件输入/输出

6.1 if语句

if 有两种格式:if和if else。
语法格式:

if (test-condition)
  statement

如果test-condition为true,程序执行statement,statement可以是一条语句也可以是语句块;如果test-condition为false,则程序将跳过statement。if测试条件同循环测试条件被强制转换为bool值,即0被转换为false,非0则为true。

6.1.1 if else语句

if语句让程序块是否执行特定的语句或语句块,而if else让程序决定执行两条语句或语句块中的某一条。二者取其一。
语法格式:

if (test-condition)
  statement1
else
  statement2

测试条件为true或非零,程序执行statement1,跳过statement2;测试条件为false或0,程序跳过statement1,执行statement2。
statement(1和2)可以是一条语句,也可以是“{}”括起来的语句块。
注意多条语句时必须用大括号括起来。

#include <iostream>
using namespace std;

int main(void)
{
char ch;

cin.get(ch);
while(ch !=.)
{
    if(ch == ‘\n’)
        cout << ch;
    else
        cout << ++ch;
    cin.get(ch);
}
cout << “Please ”<<endl;
return 0;
}

6.1.2 if else if else语句

if (ch == ‘A’)
   a_grade++;
else
   if (ch == ‘B’)
     b_grade++;
   else
      soso++;     //A、B都不成立

等价于:

if (ch == ‘A’)
   a_grade++;
else if (ch == ‘B’)
     b_grade++;
   else
      soso++;   //A、B都不成立

条件运算符和错误防范
if(3 == myNumber)等价于if(myNumber == 3)。但如果错误使用为if(3 = myNumber),编译器将生成错误消息(因为不能将一个值赋给一个字面值,3总是等于3,不能将另一个值赋给它);而如果使用if(myNumber = 3)编译将不会报错,且条件永远为真,此时可能发生难以发现的错误。

6.2 逻辑表达式

针对需要测试多种条件。

6.2.1 逻辑OR运算符:||

C++采用逻辑OR运算符||,将两个表达式组合在一起。如果原来的表达式中任意一个或全部为true(或非零),则得到的表达式值为true;否则,表达式值为false。

5 == 5||5 == 9

程序执行到5==5为true时即返回true,不会再判断后续表达式。

6.2.2 逻辑AND运算符:&&

C++采用&&逻辑AND运算符将两个表达式组合成一个表达式。仅当原来的两个表达式都为true时,得到的表达式的值才为true。

5 == 5&&4 == 4

建议都加上括号以免产生歧义。

6.2.4 逻辑NOT运算符:!

C++采用!运算符将它后面的表达式的真值取反。如果expression为true(非零),则!expression为false;反之,!expression为true。

if  (!(x>5))        //if (x < =5 )is clearer

6.3 字符函数库cctype

继承自C语言的一个与字符相关的函数软件包。在头文件cctype中定义。
在这里插入图片描述
6.4 ?:运算符
常用来代替if else语句的运算符?:,C++中唯一一个需要3个操作数的运算符。
语法格式:

expression1 ? expression2 : expression3

如果expression1,整个表达式值为expression2的值;否则,整个表达式的值为expression3的值。
例子:

5 >3 ? 10 : 12     //整个表达式值为10

比较两者较大值:

#include <iostream>
using namespace std;
int main(void)
{
  int a,b;
  int c;
  cout << “Enter two ingtegers”;
  cin >> a >> b;
  c = a > b ? a : b ;    //如果表达式a>b为真返回a给c,否则返回b给c。
  cout << “The lager  is ” << c << endl;
  return 0;
}

6.5 switch语句

switch通用格式:

switch (interger-expression)
{
case labe1 : statement(s)
case lable2 : statement(s)default :statement(s)
}

如果integer-expression的值为2,程序将执行标签为case4行的语句;如果integer-expression不与任何标签匹配,则跳到default那一行。
标签都必须是整数常量表达式,常见标签时int或char常量(1或‘q’),也可以是枚举量;default标签可选,如果被省略,而又没有匹配的标签,程序将跳到switch后边的语句处执行。

6.5.1 将枚举量用作标签

当switch语句将int值和枚举量标签进行比较时,将枚举量提升为int。同while循环测试条件,也会将枚举量提升为int类型。

#include <iostream>
using namespace std;
enum{red, orange, yellow, green, blue, violet, indigo};
int main(void)
{
cout << “Enter color code (0-6):;
cin >> code;

while(code >= red && code <= indigo)
{
     switch(code) 
     {
           case red: cout << “You choose red.<< endl; break;    //代码量很少,break可直接写在一行
           case orange: cout << “You choose orange. << endl; break;
           case yellow: cout << “You choose yellow. << endl; break; 
case green: cout << “You choose green. << endl; break;
           case blue: cout << “You choose blue. << endl; break;
           case violet: cout << “You choose violet. << endl; break;
           case indigo: cout << “You choose indigo. << endl; break;
      }
}
}

swtich语句中的每一个case标签都必须是一个单独的值(整数包括char),因此switch无法处理浮点测试。
如果既可以使用if else if语句,也可以是使用switch语句,则当选项不少于3个时,应当使用switch语句

6.6 break和continue语句

breakcontinue都可以使程序能够跳过部分代码:可在switch和任何循环中使用break语句,结束所有循环,使程序跳到switch或循环后面的语句处执行;continue则是让程序跳过循环体中余下的代码,结束本次循环,并开始新一轮循环。
在这里插入图片描述
6.7 读取数字的循环
编写一个将一系列数字读入到数组中的程序,并允许用户在数组填满之前结束输入。

#include <iostream>
using namespace std;
int main(void)
{
   int num1, int num2;
   
   cout << “First number:;
   cin >> num1;
   
   cin.clear();     //reset input
   while(cin.get() != ‘\n’);      //get rid of bad input(读取除了回车的所有输入,缓冲区便为空了)
   
   cout << “Last number:;
   cin >> num2;
   
   cout << “num1 =<< num1 <<, num2 =<< num2 << endl;
}

例如,假设程序要求用户提供5个高尔夫得分以计算平均成绩。如果用户输入非数字输入,程序将拒绝,并要求用户继续输入数字。
分析:可使用cin输入表达式的值来检测输入是否是数字,当程序发现用户输入了错误内容时,应采取以下3个措施:

  1. 充值cin以接受新的输入
  2. 删除错误输入
  3. 提示用户再输入
#include <iostream>
using namespace std;
const int Max = 5;
int main(void)
{
   int golf[Max]
   
   cout << “Please enter your golf scores.<< endl;
   cout << “You must enter ” << Max << “rounds.<< endl;

   int i;
   for(i = 0; i<Max; i++)
   {
cout << “Round #” << i + 1 <<;<< endl;
while(!(cin >> golf[i]))
{
           cin.clear();     //reset input
           while(cin.get() != ‘\n’);      //get rid of bad input(读取除了回车的所有输入,缓冲区便为空了)
           cout << “Please enter a number://直到输入正确数字后跳出循环
}
}
double total = 0;
for(i = 0; i < Max; i++)
   total += golf[i];
cout << “Average score:<< total / max <<.<< endl;
    return 0;
   }

6.8 简单文件输入/输出

6.8.1 文本I/0和文本文件

给定输入行:

38.5 19.2

cin使用不同数据类型变量存储:
char类型

char ch;
cin >> ch;
//

输入行的第一个字符数字3被赋给ch,其字符编码(二进制)被存储在ch中。输入和目标变量都是字符,此处不需要转换。注意此处存储的不是数值3,而是字符3的编码.
int类型

int n;
cin >> n;
//

cin将不断读取,直到遇到非数字字符。此处将读取3和8,句点则成为输入队列中的下一个字符。即将数值38(的二进制编码)存到n中。
double类型

double x;
cin >> x;
//

cin将不断读取,直到遇到不属于浮点数的字符。此处将读取3、8、句点和5,空格则成为输入队列中的下一个字符。即将数值38.5(的二进制编码)存到x中。
char数组

char word[50];
cin >> word;
//

cin将不断读取,直到遇到空白字符(空格、tab、回车)。此处将读取3、8、句点和5,空格 则成为输入队列中的下一个字符。即将该4个字符的字符编码存储到数组word中,并在末尾加上一个空字符。此处不需要转换。
char数组cin.getline()

char word[50];
cin.getline(word, 50);
//

cin将不断读取,直到遇到换行符。所有字符都将被存储到数组word中,并在末尾加上一个空字符。之后换行符被丢弃,输入队列中的下一个字符是下一行中第一个字符。此处不需要转换。
总结:对于输入,整数被转换为数字字符序列,浮点数转换为数字字符和其他字符组成的字符序列(如28.5);字符数据不需做任何转换。

6.8.2 写入到文本文件中

使用文本输出主要步骤:

  1. 包含头文件
  2. 创建一个ofstream对象
  3. 将该ofstream对象关联一个文件
  4. 通过使用cout的方式使用该ofstream对象。
    产生关联后,outFile用法和cout用法一样,所有可用于cout的操作和方法都可以用于ofstream对象。
    例如:
#include <iostream>     //ostream->cout,istream->cin,cin和cout都定义好了
#include <fstream>       //1.includeo<fstream>  //ofstream,ifstream
using namespace std;

int main(void)
{
char automobile[50];
int year;
double a_price;
double d_price;

//outFile用法和cout用法一样,区别在于一个写入到文本中,一个打印到屏幕
ofstream outFile;         //2.创建一个ofstream对象
outFile.open(“carinfo.txt”);          //3.将对象关联文件
cout << “Enter the make and model of automobile :;
cin.getline(automobile, 50);    //此处可能有空格,所以用getline捕获一整行
cout << “Enter the model year:;
cin >> year;
cout << “Enter the original asking price:;
cin >> a_price;
d_price = a_price * 0.913;
 
//show on screen
cout << fixed;    //小数点显示
cout.precision(2);  //小数点保留2位
cout.setf(ios_base:showpoint);     //即使小数点为0也要显示为.00
cout << “Make and model :<< automobile << endl;
cout << “Year:<< year << endl;
cout << “Was asking :<< a_price << endl;
cout << “Now asking :<< d_price << endl; 

// show on txt

outFile << fixed;    //小数点显示
outFile.precision(2);  //小数点保留2位
outFile.setf(ios_base::showpoint);     //即使小数点为0也要显示为.00
outFile << “Make and model :<< automobile << endl;
outFile << “Year:<< year << endl;
outFile << “Was asking :<< a_price << endl;
outFile << “Now asking :<< d_price << endl; 

outFile.close();  //此处也可不加,加了是为和open()成对出现,程序好看
return 0}

open()方法:

outFile.open(“carinfo.txt”);

上述程序运行之前,文件carinfo.txt并不存在,open()新建一个名为carinfo.txt的文件;如果文件carinfo.txt已存在,open()将将其长度截短到0,清空原有内容,然后将新的输入写入到该文件中。

6.8.3 读取文本文件

产生关联后,inFile用法和cin用法一样,所有可用于cin和方法都可以用于ifstream对象。

#include <iostream>     //ostream->cout,istream->cin,cin和cout都定义好了
#include <fstream>       //1.includeo<fstream>  //ofstream,ifstream
#include <cstdlib>
using namespace std;

const int SIZE = 60;

int main(void)
{
char filename[SIZE]

ifstream inFile;    //2.创建一个ifstream对象
cout << “Enter name of data file:;
cin.getline(filename, SIZE);
inFile.open(filename);     //3.将对象关联文件
if(!inFile.is_open())
{
   cout << “Faild to open the file ” << filename << endl;
   cout << “Program terminating.<< endl;
       exit(EXIT_FAILURE);     //#include <cstdlib>
}
cout << “Open the file successfully.<< endl;
double value;
double sum = 0.0;
int count = 0;

inFile >> value;        //get first value
while(inFile.good())      //while input good and not at EOF,整个txt所以用while//读取是否成功
{
    ++count;
    sum += value;
    inFile >> value;
}
if(inFile.eof())              //读到了文件末尾,即文件全部读取成功
    cout << “End of file reached.<< endl;
else if(inFile.fail)           //读取过程中失败,读取数据和存储变量格式不匹配
    cout << “Input terminated by data mismatch.<< endl;
else 
    cout << “Input terminated by unkown reason” << endl;
if(count == 0)
    cout << “No data processed.<< endl;
else
{
    cout << “Iterms read:<< count << endl;
    cout << “Sum:<< sum << endl;
cout << “Average:<< sum / count << endl;
}

inFile.close();       //和open成对出现
return 0}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我宿孤栈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值