1. 程式人生 > >Windows系統對拍程序

Windows系統對拍程序

key lib 測試 ++ mos 環境變量 代碼 列表 out

Windows系統對拍程序,其中包含c++11用法,請使用c++11編譯。

此對拍程序自動使用g++對源代碼進行編譯。如果出現找不到g++錯誤,請將g++所在目錄添加至系統的環境變量列表中。

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <cstdlib>
 4 #include <ctime>
 5 
 6 // 設置區
 7 namespace Settings {
 8     const int MAX_LEN = 20; // 當發現錯誤時,顯示錯誤行數據的最大長度
 9     const
int CASE_CNT = 100; // 測試次數 10 const int BUFFER_SIZE = 1 << 10; // 每行的緩沖區大小 11 const char *const testFile = "1.cpp"; // 需要測試的源代碼文件名 12 const char *const stdFile = "2.cpp"; // 標準答案的源代碼文件名 13 const char *const dataFile = "3.cpp"; // 隨機生成數據的源代碼文件名 14 } 15 16 using namespace Settings; 17 using
namespace std; 18 char cmd[BUFFER_SIZE], info[BUFFER_SIZE]; 19 char buf1[BUFFER_SIZE], buf2[BUFFER_SIZE]; 20 21 template <typename ...T> 22 int run(const char *str, T ...args) { 23 sprintf(cmd, str, args...); 24 return system(cmd); 25 } 26 27 bool fileCompare(const char *stdOutput, const
char *userOutput) { 28 FILE *fp_std = fopen(stdOutput, "r"), *fp_user = fopen(userOutput, "r"); 29 if (fp_std == nullptr || fp_user == nullptr) { 30 perror(nullptr); 31 return false; 32 } 33 for (int i = 1; !feof(fp_std) && !feof(fp_user); ++i) { 34 char *p1 = fgets(buf1, BUFFER_SIZE, fp_std); 35 char *p2 = fgets(buf2, BUFFER_SIZE, fp_user); 36 if (p1 == nullptr && p2 == nullptr) { 37 return true; 38 } else if (!p1 || !p2 || strcmp(p1, p2)) { 39 sprintf(info, 40 "Difference found in line %d:\n std: %.*s user: %.*s", 41 i, MAX_LEN, p1 ? p1 : "(EOF Detected)\n", 42 MAX_LEN, p2 ? p2 : "(EOF Detected)\n"); 43 break; 44 } 45 } 46 return false; 47 } 48 49 int main() { 50 printf("Compiling... "); 51 run("g++ %s -o test.exe", testFile); 52 run("g++ %s -o std.exe", stdFile); 53 run("g++ %s -o data.exe", dataFile); 54 printf("Finished.\n"); 55 clock_t st, ed; 56 for (int i = 1; i <= CASE_CNT; ++i) { 57 printf("Case %03d: ", i); 58 run("data.exe >data.txt"); 59 run("std.exe <data.txt >std.txt"); 60 st = clock(); 61 run("test.exe <data.txt >test.txt"); 62 ed = clock(); 63 if (!fileCompare("std.txt", "test.txt")) { 64 printf("Wrong Answer.\n------------------------------\n"); 65 puts(info); 66 printf("------------------------------\nNote: At most %d characters will be shown for both lines.\n", MAX_LEN); 67 printf("Press anykey to exit.\n"); 68 getchar(); 69 break; 70 } else { 71 printf("Accepted. Time: %dms.\n", int(ed - st)); 72 } 73 } 74 return 0; 75 }

Windows系統對拍程序