[摘]BruceEckel专门为《C++编程思想》写的一个错误检查头文件

本文介绍了一个专门用于C++程序错误检查的头文件,该文件包含多种实用的检查函数,如require和assure,帮助开发者确保程序符合预期条件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Code:
  1. //: :require.h  
  2. // From Thinking in C++, 2nd Edition  
  3. // Available at http://www.BruceEckel.com  
  4. // (c) Bruce Eckel 2000  
  5. // Copyright notice in Copyright.txt  
  6. // Test for error conditions in programs  
  7. // Local "using namespace std" for old compilers  
  8. #ifndef REQUIRE_H  
  9. #define REQUIRE_H  
  10. #include <cstdio>  
  11. #include <cstdlib>  
  12. #include <fstream>  
  13. #include <string>  
  14.   
  15. inline void require(bool requirement,   
  16.   const std::string& msg = "Requirement failed"){  
  17.   using namespace std;  
  18.   if (!requirement) {  
  19.     fputs(msg.c_str(), stderr);  
  20.     fputs("/n", stderr);  
  21.     exit(1);  
  22.   }  
  23. }  
  24.   
  25. inline void requireArgs(int argc, int args,   
  26.   const std::string& msg =   
  27.     "Must use %d arguments") {  
  28.   using namespace std;  
  29.    if (argc != args + 1) {  
  30.      fprintf(stderr, msg.c_str(), args);  
  31.      fputs("/n", stderr);  
  32.      exit(1);  
  33.    }  
  34. }  
  35.   
  36. inline void requireMinArgs(int argc, int minArgs,  
  37.   const std::string& msg =  
  38.     "Must use at least %d arguments") {  
  39.   using namespace std;  
  40.   if(argc < minArgs + 1) {  
  41.     fprintf(stderr, msg.c_str(), minArgs);  
  42.     fputs("/n", stderr);  
  43.     exit(1);  
  44.   }  
  45. }  
  46.     
  47. inline void assure(std::ifstream& in,   
  48.   const std::string& filename = "") {  
  49.   using namespace std;  
  50.   if(!in) {  
  51.     fprintf(stderr, "Could not open file %s/n",  
  52.       filename.c_str());  
  53.     exit(1);  
  54.   }  
  55. }  
  56.   
  57. inline void assure(std::ofstream& out,   
  58.   const std::string& filename = "") {  
  59.   using namespace std;  
  60.   if(!out) {  
  61.     fprintf(stderr, "Could not open file %s/n",   
  62.       filename.c_str());  
  63.     exit(1);  
  64.   }  
  65. }  
  66. #endif // REQUIRE_H ///:~  

注:上面的这个头文件是BruceEckel专门为这本书写的一个用于错误检查的头文件,供大家参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值