您的位置:首页 > 编程语言 > C语言/C++

c++拾遗-----循环和关系表达式

2016-02-22 22:17 507 查看
1、for循环

步骤:

设置初始值

执行测试,看循环是否应当继续进行

执行循环操作

更新用于测试的值

2、副作用与顺序点

副作用:在计算表达式时对某些东西进行了更改

顺序点:是程序执行过程中的一个点,在这里,进行下一步之前确保所有的副作用都进行了评估

3、类型别名

建立类型别名的两种方法:

使用预处理器

#define BYTE char


在编译程序时用char替换BYTE

使用关键字typedef创建类型别名

typedef char byte


创建char别名byte

但#define会有以下问题

#define FLOAT_POINTER float *
FLOAT_POINTER pa,pb;


结果只有pa声明为指针,pb被声明为浮点变量,而使用typedef则没有这种问题

4、基于范围的for循环

c++11新增一种循环:基于范围的for循环,对数组(或容器类,如vector和array)的每个元素执行相同的操作。

double prices[5]={5.87,6.32,7.33,4.22,1,87};
for(double price:prices)
std::cout<<price<<std::endl;


还可以结合使用基于范围的for循环和初始化列表

for(int x:{1,2,3,4,5})
std::cout<<x<<" ";
cout<<endl;


5、文件的读写

写文件

#include<iostream>
#include<fstream>
#include<string>

int main()
{
using namespace std;
std::string filename;
ofstream outputfile;
std::cout << "input filename:";
std::cin >> filename;
outputfile.open(filename);
if (!outputfile.is_open())
{
exit(EXIT_FAILURE);
}
outputfile << "xxxxxxxxxxxxxx"<<endl;
outputfile << "ccccccccccccccc" << endl;
outputfile.close();
return 0;
}


文件不存在时会自动创建,每次写会把上次的清空,即每次都是从0位置开始写,操作完毕后调用close函数关闭文件。

读文件

#include<iostream>
#include<fstream>
#include<string>

int main()
{
using namespace std;
std::string filename;
string value = "";
ifstream inputfile;
std::cout << "input filename:";
std::cin >> filename;
inputfile.open(filename);
if (!inputfile.is_open())
{
exit(EXIT_FAILURE);
}
inputfile >> value;
cout << value;
inputfile.close();
return 0;
}


打开文件,如果文件不存在则退出。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++