C++

C++plus6th第5章_循环和关系表达式

2021-03-21  本文已影响0人  Leon_Geo

第5章 循环和关系表达式

1.关于循环

#include <iostream>
const int Arsize = 16;  //全局变量
int main()
{
    long fact[Arsize];
    for (int i = 0; i < Arsize; i++)
        std::cout << fact[i] << endl;
    return 0;
}
#include <iostream>
#include <cstring>      //老版本需使用string.h

int main()
{
    using namespace std;
    cout << "Enter a word:"
    string word;
    cin >> word;
    
    for (int i = word.size - 1; i >= 0; i--)
        cout << word[i];
    cout << endl;
    return 0;
x = 2 * x++ * (3 - ++x);    //不确定先计算x++还是++x,容易发生歧义的表达式,结果未知
*++pt;  //先将pt加1,然后取值;
++*pt;  //先取pt存储的值,然后将该值加1,pt的值不变。
*pt++;  //取出pt指向的值,然后将pt加1
#include <iostream>
#include <ctime>    //老版本中使用#include <time.h>
int main()
{
    using namespace std;
    float secs = 2.5;
    clock_t delay = secs * CLOCK_PER_SEC;
    clock_t start = clock();
    while (clock() - start < delay)
        ;
    //至此延时了2.5秒。
    cout << secs << "seconds had pasted." << endl;
    return 0;    
}

基于范围的for循环。如下例所示:

double prices[5] = {4.1, 2.3, 4.5, 6.2, 5.3};
for (double x : prices)
    cout << x << std::endl;

x在数组prices范围内依次代表数组各元素值。同时为了能够修改数组元素,可以使用引用符&,见如下例子:

double prices[5] = {4.1, 2.3, 4.5, 6.2, 5.3};
for (double &x : prices)
    x += 2.0;
//将数组中的每个元素加上2.0

2.关于类型别名

#define FLOAT_PTR float *
FLOAT_PTR pa, pb;
//经过预处理后语句2将会变成:float * pa, pb;
//而此时,pa是指针,pb却是float变量。

typedef float* float_ptr;
float_ptr pa, pb;   //不会有上述问题

3.关于cin.get()函数

该函数有三种函数原型(函数重载),即有3种不同的参数:cin.get(void)、cin.get(char &ch)、cin.get(char * array_name, int size )。

4.关于文件结束符EOF

#include <iostream>
int main()
{
    using namespace std;
    char ch;
    int count = 0;
    cin.get(ch);
    while (cin.fail() == false)
    {
        cout << ch;
        ++count;
        cin.get(ch);
    }
    cout << endl << count << "chars read\n";
    return 0;        
}
char ch;
while (cin.get(ch)) //当读取失败或读到EOF时,cin.get(ch)返回false
{
    ...
}

或者

char ch;
cin.get(ch);
while (!cin.fail())
{
    ...
    cin.get(ch);
}

或者
 
int ch;     //cin.get()返回int型
while ((ch = cin.get()) != EOF)
{
    cout.put(char(ch)); //其参数必须是char型
}
cout << endl;
上一篇 下一篇

猜你喜欢

热点阅读