6.1 if语句
if (test_condition)
statement
6.1.1 if else 语句
if(test_condition)
statement1;
else
statement2;
测试条件1为真,执行语句1,否则执行语句2
6.1.3 if ,else if , else结构
6.2 逻辑表达式
- 逻辑OR操作符:||
- 逻辑AND 操作符:&&
- 逻辑NOT操作符:!
6.3 字符函数库(cctype)
6.4 ?:操作符
可以替代if else语句。
expression1 ? expression2 :expression3;
如果expression1为true,则执行expression2,否则执行expression3;
6.5 switch 语句
switch (interger_expression)
{
case label1 : statement(s)
case label2 : statement(s)
case label3 : statement(s)
...
default : statement
}
如果测试条件与任何情况都不匹配,则直接跳到default;
6.5.1 用枚举量作为标签
#include <iostream>
enum{ red,orange,yello,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 was red.\n"; break;
case orange: cout << "Her hair was orange.\n"; break;
case yello: cout << "Her shoes was yello.\n"; break;
case green: cout << "Her sweatsuit was green.\n"; break;
case blue: cout << "Her nails was blue.\n"; break;
case violet: cout << "Her eyes was violet.\n"; break;
case indigo: cout << "Her mood was indigo.\n"; break;
}
cout << "Enter color code(0-6):";
cin >> code;
}
cout << "Bye!\n";
return 0;
}
6.6 break和contiune语句
break直接跳出循环;
contiune跳过该次循环剩余的部分,直接开始下一轮循环。
6.7 读取数字的循环
6.8 简单文件输入和输出
6.8.2 写入到文本文件中
输入准备:
- 头文件包含iostream
- 指明空间std;
- 包含头文件fstream
- 使用完文件后,应使用close关闭
#include <iostream>
#include <fstream>
using namespace std;
...
ofstream out.File; //创建输出文件
outFile.open("fish.txt"); //用outFile 写入磁盘文件fish.txt
outFile<<***; //将***写入文件中
outFile.close(); //关闭文件
6.8.3 读取文本文件
- 包含头文件iostream
- 包含头文件fstream
- 知明名称空间std
如下例:
#include <iostream>
#include <fstream>
#include <cstdlib> //使得exit(EXIT_FAILURE)有效
using namespace std;
const int size = 50;
int main()
{
using namespace std;
char filename[Size];
ifstream inFile; //用于处理输入的对象
cout << "Enter name of data file: ";
cin.getline(filename, Size);
inFile.open(filename); //将inFile 与文件联系起来,即从文件中读取内容
//如果读取失败,则退出程序
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; //读取下一个字符
}
if (inFile.eof())
cout << "End of file reached.\n";
else if (inFile.fail())
cout << "Input terminated by data mismatch.\n";
else
cout << "Input terminatd 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;
}