c++基础知识(4)

c++ primer plus第五、六章,包括for循环、while循环、if语句、字符函数库、switch语句、break和continue等。

for循环

1
2
3
4
for(initialization; test-expression; update-expression)
{
body
}

while循环

1
2
3
4
while(test-expression)
{
body
}

for循环和while循环基本上是等效的。

在无法预先知道循环将执行的次数时,常使用while循环

类型别名:

  • ①使用预处理器:#define
  • ②使用关键字typedef:typedef typeName aliasName

在声明一系列变量时,使用#define的方法不适用

1
2
#define FLOAT_POINTER float *;
FLOAT_POINTER pa,pb;//等效于 float *pa,pb;

do while 循环

出口条件循环:循环至少执行一次

1
2
3
4
do
{
body
}while(test-expression);

基于范围的循环

简化一种常见的循环任务:对数组(或容器类,如vector和array)的每个元素执行相同的操作

1
2
3
4
5
double prices = {4.99, 10.99, 6.78, 8.56, 9.40};
for (double x : prices)
{
cout << x std::endl;
}

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

1
2
3
4
for (double &x : prices)
{
x = x * 0.80;
}

符号&表明x是一个引用变量

循环和文本输入

使用原始的cin进行输入

使用循环读取来自键盘的文本输入,通过哨兵字符作为停止标记。

例如当输入#字符时停止读取输入

cin在读取char值时,与读取其他基本类型一样,将忽略空格和换行符。

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

cin.get(ch)读取输入中的下一个字符(即使是空格),并将其赋给变量ch。

EOF

检测到EOF后,cin将两位(eofbit和failbit)都设置为1,则fail()成员函数返回true,否则返回false。

1
2
3
4
5
while(cin.fail == false)
{
cout << ch;
count++;
}

if语句

1
2
3
4
if(test-condition)
{
statement
}
1
2
3
4
5
6
7
8
if(test-condition)
{
statement 1
}
else
{
statement 2
}
1
2
3
4
5
6
7
8
if(test-condition)
{
statement 1
}
else if
{
statement 2
}

逻辑表达式

逻辑OR运算:||、逻辑AND运算:&&、逻辑NOT运算符:!

1
if(17<age<35) //×

字符函数库cctype

需要添加头文件cctype

函数名称 返回值
isalnum() 如果参数是字母或数字,函数返回true
isalpha() 如果参数是字母,函数返回true
iscntrl() 如果参数是控制字符,函数返回true
isdigital() 如果参数是数字(0-9),函数返回true
isgraph() 如果参数是除空格之外的打印字符,函数返回true
islower() 如果参数是小写字母,函数返回true
isprint() 如果参数是打印字符(包括空格),函数返回true
ispunct() 如果参数是标点符号,函数返回true
isspace() 如果参数是标准空白字符,如空格、换行符、回车、水平制表符或者垂直制表符,函数返回true
isupper() 如果参数是大写字母,函数返回true
isxdigit() 如果参数是十六进制数字,函数返回true
tolower() 如果参数是大写字母,则返回其小写,否则返回该参数
toupper() 如果参数是小写字母,则返回其大写,否则返回该参数

?:运算符

1
expression1 ? expression2 : expression3;

如果expression1为true,则整个条件表达式的值为expression2的值;否则,整个表达式的值为expression3的值。

switch语句

1
2
3
4
5
6
7
switch(integer-expression)
{
case lable1 : statement(s)
case lable2 : statement(s)
...
default : statement(s)
}

switch并不是为处理取值范围而设计的,且无法处理浮点测试

break和continue语句

break结束循环

continue结束该轮循环,开始下一轮循环

在for循环中,continue语句导致该程序跳过循环体的剩余部分,但不会跳过循环的更新表达式

简单文件输入/输出

写入到文本文件

1
2
3
4
#include<fstream>
ofstream outFile;//creat object of output file stream
outFile.open("fish.txt"); // associate with a file
outfile << "write to the file successful!";

多次运行,会覆盖原来的内容

读取文本文件

1
2
3
4
5
6
7
8
#include<fstream>
#include<iostream>
char filename[60];
ifstream inFile;
cin.getline(filename, 60);
inFile.open(filename);

inFile.close();

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!