1 for
循环
// introducing the for loop
#include <iostream>
int main()
{
using namespace std;
int i; // create a counter
// initialize; test; update
for (i = 0; i < 5; i++)
cout << "C++ knows loops.\n";
cout << "C++ knows when to stop." << endl;
return 0;
}
C++不限制test-expression的值,它将结果强制转换为bool
类型。
for
循环是入口条件(entry-condition)循环——每轮循环之前都将计算测试表达式的值。更新表达式(update-expression)在每轮循环结束时执行,此时循环体已经执行完毕。
递增运算符++
和递减运算符--
前缀版本位于操作数前;后缀版本位于操作数后。前缀表达式值为操作数加/减1,后缀表达式值为操作数。
前缀和后缀格式的执行速度在类上有差别。前缀函数:值加1返回结果;后缀函数:复制一个副本,加一,返回副本。因此,前缀版本比后缀版本效率高。
2 while
循环
while(name[i] != '\0')
{
cout << name[i] << ": " << int(name[i]) << endl;
i++;
}
C++建立类型别名的方式:
- 使用预处理器
- 使用
typeof
关键字
#define BYTE char // preprocessor replaces BYTE with char
typedef char byte; // make byte an alias for char
// typedef不会创建新类型,只是为已有的类型建立一个新名称。
3 do while
循环
do
{
cin >> n;
} while (n != 7);
4 基于范围的for
循环(C++11)
对数组(或容器类)的每个元素执行相同的操作
double prices[5] = {4.9, 10.9, 6.78, 7.9, 8.4};
for (double x : prices)
cout << x << std::endl;
// 修改数组元素
for (double &x : prices) // &表明x是一个引用变量
x = x * 0.8
循环和文本输入
// reading chars with a while loop
#include <iostream>
int main()
{
using namespace std;
char ch;
int count = 0;
cout << "Enter characters; enter # to quit:\n";
cin >> ch;
// 选择一个哨兵字符做为停止标记
while(ch != '#'){
cout << ch;
++count;
cin >> ch;
}
cout << endl << count << " characters read\n";
return 0;
}
cin
在读取基本类型时,将忽略空格和换行符。另外,发送给cin
的输入被缓冲,即只有在用户按下回车键后输入的内容才会被发送给程序。
// using cin.get(char)
#include <iostream>
int main()
{
using namespace std;
char ch;
int count = 0;
cout << "Enter characters; enter # to quit:\n";
cin.get(ch); // 该函数调用将修改变量的值;函数声明中将参数声明为引用
while(ch != '#')
{
cout << ch;
++count;
cin.get(ch);
}
cout << endl <<count << " characters read\n";
return 0;
}
包括空格在内的字符都被接收,但是输入仍然被缓冲。
如果输入来自于文件,可以检测文件尾(EOF)来判断输入是否结束。C++输入工具和操作系统协同工作来检测文件尾并将这种信息告知程序。
检测到EOF后,cin
将两位(eofbit
和failbit
)都设置为1。设置后,cin
将不读取输入。如果稍后要读取其他输入,cin.clear()
方法可能清除EOF标记使输入继续进行。
// reading chars to end of file
#include <iostream>
int main()
{
using namespace std;
char ch;
int count = 0;
cin.get(ch);
while(cin.fail() == false) // test for EOF
{
cout << ch;
++count;
cin.get(ch);
}
cout << endl << count << " characters read\n";
return 0;
}
istream
类提供了一个可以将istream
对象(如cin
)转换为bool
值的函数。当该对象出现在需要`bool=值的地方,该转换函数将被调用。
while(cin.get(ch))
{
cout << ch;
++count;
}