内容思维导图
1. if语句
if (test-condition)
statement
if (test-condition)
statement1
else
statement2
2. 逻辑表达式
- C++提供3种路逻辑操作符
- C++规定,
||操作符是一个顺序点(sequence point),也就是说,先修改左侧的值,然后对右侧的值进行判定。
- 逻辑操作符的另一种表示方式:
| 操作符 |
替换代表 |
| && |
and |
| | |
or |
| ! |
not |
3. 字符函数库cctype
| 函数名称 |
返回值 |
| isalnum() |
如果参数是字母数字,即字母或数字,该函数返回true |
| isalpha() |
如果参数是字母,该函数返回true |
| isblank() |
如果参数是空格或水平制表符,该函数返回true |
| iscntrl() |
如果参数是控制字符,该函数返回true |
| isdigit() |
如果参数是数字(0~9),该函数返回true |
| isgraph() |
如果参数是除空格之外的打印字符,该函数返回true |
| islower() |
如果参数是小写字母,该函数返回true |
| isprint() |
如果参数是打印字符(包括空格),该函数返回true |
| ispunct() |
如果参数是标点符号,该函数返回true |
| isspace() |
如果参数是标准空白字符,如空格、进纸、换行符、回车、水平制表符或者垂直制表符,该函数返回true |
| isupper() |
如果参数是大写字母,该函数返回true |
| isxdigit() |
如果参数是十六进制的数字,即09、af或A~F,该函数返回true |
| tolower() |
如果参数是大写字符,则返回其小写,否则返回该参数 |
| toupper() |
如果参数是小写字符,则返回其大写,否则返回该参数 |
4. ?:操作符
- C++有一个常用来代替
if else语句的操作符,被称为条件操作符(?:),它是C++中唯一一个需要3个操作数的操作符,其通用格式如下:
expression1 ? expression2 : expression3
// 以下条件语句与if else语句等效
int c = a > b ? a : b;
int c;
if (a > b)
c = a;
else
c = b;
5. switch语句
switch (integer-expression)
{
case label1: statement(s)
case label2: statement(s)
...
default: statement(s)
}
-
integer-expression必须是一个结果为整数值的表达式,另外,每个标签都必须是整数常量表达式。
- C++中的
case标签只是行标签,而不是选项之间的界限,也就是说,程序跳到switch中特定代码行后,将依次执行之后的语句,除非有明确的其他指示。
6. 简单的文本输入/输出
- 使用文件输出的主要步骤如下:
- 包含头文件
fstream
- 创建一个
ofstream对象
- 将该
ofstream对象同一个文件关联起来
- 就像使用
cout那样使用该ofstream对象
#include <fstream>
int main()
{
ofstream outFile; // 创建对象
outFile.open("carinfo.txt"); // 关联文件
outFile << fixed;
outFile.precision(2);
outFile.setf(ios_base::showpoint);
outFile << "input something into file.";
outFile.close(); // 关闭文件
return 0;
}
- 读取文件有几点需要检查:
- 程序读取文件时不应超过
EOF。
- 程序可能遇到类型不匹配的情况。
- 某些预期外的东西可能出现问题,如文件受损或硬件故障。
- 使用方法
good()可以检查上述情况。
- 文件读取循环设计
inFile >> value; // 获取第一个值
while (inFile.good()) // 测试输入是否正常且不是EOF
{
// 循环体
inFile >> value; // 读取下一个值
}
// 精简版
// 在需要bool值时,inFile的结果为inFile.good()的结果
while (inFile >> value) // 读取和测试
{
// 循环体
}