代码在AS上运行的

异常

四种异常抛出方法

  1. #include <iostream>
  2. #include <string>
  3. #include "mylog.h"
  4. #include "main_03.h"
  5. using namespace std;
  6. //异常测试
  7. void exceptionMethod01() {
  8. throw "我抛出了异常";
  9. }
  10. //异常测试2
  11. void exceptionMethod02() {
  12. throw exception();
  13. }
  14. //异常测试3 --自定义异常
  15. class CustomException : public exception {
  16. public:
  17. const char *what() const noexcept override {
  18. return "我要抛出自定义异常了";
  19. }
  20. };
  21. void exceptionMethod03() {
  22. throw CustomException();
  23. }
  24. //异常测试4 自定义异常
  25. class Student {
  26. public:
  27. char *getInfo(){
  28. return "自定义异常4";
  29. }
  30. };
  31. void exceptionMethod04(){
  32. Student s;
  33. throw s;
  34. }
  35. void main_03() {
  36. try {
  37. exceptionMethod01();
  38. } catch (const char *errMsg) {
  39. LOG("捕获到了异常信息:%s", errMsg);
  40. }
  41. try {
  42. exceptionMethod02();
  43. } catch (exception &errMsg) {
  44. LOG("捕获到了异常信息:%s", errMsg.what());
  45. }
  46. try {
  47. exceptionMethod03();
  48. } catch (CustomException &errMsg) {
  49. LOG("捕获到了异常信息:%s", errMsg.what());
  50. }
  51. try {
  52. exceptionMethod04();
  53. } catch (Student &errMsg) {
  54. LOG("捕获到了异常信息:%s", errMsg.getInfo());
  55. }
  56. }

IO流

image.png
image.png
image.png

IO缓冲区

image.png

cin.ignore(numeric_limits::max(), ‘\n’); //清空缓冲区脏数据

文件操作

image.png
image.png

文件操作步骤

image.png

文件打开方式

image.png

文本文件的操作

  1. char a;
  2. int index = 0;
  3. fstream fout;
  4. fout.open("testBuffer.txt", ios::app);
  5. if(fout.fail()){
  6. cout << "The file open fail" << endl;
  7. }
  8. while (cin >> a) {
  9. // cout << "in while:" << a << endl;
  10. fout << "in while: " << a << endl;
  11. index++;
  12. if (index == 5) {
  13. break;
  14. }
  15. }
  16. cin.ignore(numeric_limits<streamsize>::max(), '\n'); //清空缓冲区脏数据
  17. char ch;
  18. cin >> ch;
  19. // cout << "out while:" << ch << endl;
  20. fout << "out while:" << ch << endl;
  21. fout.close();

二进制文件的操作

  1. #include <fstream>
  2. bool CopyFile(const string& str, const string& dst){
  3. ifstream in(str.c_str(), std::ios::in | std::ios::binary);
  4. ofstream out(dst.c_str(), std::ios::out | std::ios::binary | std::ios::trunc);
  5. if(!in || !out){
  6. return false;
  7. }
  8. char temp[bufferLen];
  9. while (!in.eof()){
  10. in.read(temp, bufferLen);
  11. streamsize count = in.gcount();
  12. out.write(temp, count);
  13. }
  14. in.close();
  15. out.close();
  16. return true;
  17. }