VC++ (main.cpp):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 | #include "stdafx.h" #include <iostream> #include <regex> #include <fstream> using namespace std; class pos { public : float x; float y; float z; }; class ERR { private : int kind; public : ERR( int k) : kind(k){}; //建構函式 char * message() { switch (kind) { case 0: return "Error A" ; case 1: return "Error B" ; case 2: return "Error C" ; } } }; void readfile(string path) { string lines = "" ; ifstream File(path); if (File.is_open()) //Check File { while (File.good()) { getline(File, lines); cout << lines << endl; } File.close(); } } int main( int argc, char *argv[]) { switch (0) //Select Example { case 0: { //Example 1 int n = 0; string str = "Hello" ; try { cin >> n; cout << str.at(n) << endl; //取得字串的第n個字元 } catch (...) { cout << "Error!" << endl; } break ; } case 1: { //Example 2 float num = 1; try { cout << "num=" ; cin >> num; if (num == 0) { throw "Infinity!" ; } cout << "100/num=" << 100/num << endl; } catch ( const char * message) { cout << message << endl; } break ; } case 2: { //Example 3 try { if (argc<2) { throw "Parameter error." ; } char pathChar[1024]; regex pathRegex( "([a-zA-Z]\:\\\\(?:[^\\\\]+\\\\)*.*)" ); //"C:\\temp\\hello.txt" cmatch pathMatch; //cmatch: Char Match strcpy (pathChar, argv[1]); //Pointer to Char if (regex_match(pathChar, pathMatch, pathRegex)) //char, cmatch, regexp { readfile(pathMatch[1].str()); } else { throw "Path Error." ; } } catch ( const char * message) { cout << message << endl; } break ; } case 3: { //Example 4 pos p; p.x = 1.1f; p.y = 2.2f; p.z = 3.3f; cout << "(" << p.x << ", " << p.y << ", " << p.z << ")" << endl; break ; } case 4: { //Example 5 try { throw ERR(0); } catch (ERR e) { cout << e.message() << endl; } break ; } } system ( "pause" ); return 0; } |
說明:
一般及搭配argc、argv、Regular Expression、Class例外處理的方法
沒有留言:
張貼留言