您的位置:首页 > 其它

错误检查

2016-05-05 21:09 274 查看
#ifndef COS_H_
#define COS_H_

#include <string>
#include <fstream>
#include <cstdlib>

inline void require(bool requirement, const std::string& msg = "Requirement failed")
{
if (!requirement)
{
fputs(msg.c_str(), stderr);
fputs("\n", stderr);
system("pause");
exit(1);
}
}

inline void assure(std::ifstream& in, const std::string& filename = "") // 这个就是文件输入流的检查,
{
if (!in)
{
std::cout << "Could not open file." << std::endl;
exit(1);
}
}

inline void assure(std::ofstream& out, const std::string& filename = "")  // 这就是错误检查函数,
{

}

#endif


#include <iostream>
#include <cassert>
#include <fstream>
#include "cos.h"

using namespace std;

#define SRUARE (x) (x)*(x)  // 这个是C语言的预定义宏,是计算x*x的,它有缺点。总是出错,

inline double square(double x)  // 在函数前边加上inline就是内联函数,内联函数在编译的时候执行,内联函数主要是为了加快执行的速度,
{
double result;
result = x * x;
return result;
}

int main()
{
char* linePtr = (char *)malloc(1024);  // malloc 是动态分配内存,
//if (linePtr == NULL)  // 这个就是检查linePtr 指针是否出错,
//{
//	cout << "malloc 失败。" << endl;
//	return 0;
//}
//  assert(linePtr != 0); // assert 断言,
require(linePtr != 0, "动态分配内存失败,"); //假如linePtr 是等于0,将输出的是 "动态分配内存失败,"

string inFileName = "a.txt";
ifstream in(inFileName);
assure(in,inFileName); // 这个就是调用cos.h头文件里的判断头文件是否存在,

double c(6.0);
cout << square(c) << endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: