如何自制一个评测机
大家都知道 OJ 评测程序的时候,输入都是从文件中读取的, 但我们平时写程序的时候都是用 STDIO 进行输入输出的。那如何在不改变程序的前提下,重定向输入输出呢?
这时候命令行工具就派上用场了。
在C++中有个函数叫做 system,返回值是一个 int,也就是命令执行完成后返回的错误码。
下面只讨论 windows 的命令行 cmd。
除此以外 cmd 还支持管道操作符|
所以我们可以用这样一行 cmd 命令完成输入输出
type in.txt | example.exe > out.txt代码示例
#include <bits/stdc++.h>
using namespace std;
const int AC=0;
const int TLE=1;
const int WA=2;
const int RE=3;
int test(string prg,string in,string out,string ans,int sec,int &t){
string cmd="type \""+in+"\" | \""+prg+"\" > \""+out+"\"";
long long st=time(0);
int ok=system(cmd.c_str());
long long ed=time(0);
t=ed-st;
if(ok!=0) return RE;
ifstream str1(out.c_str());
ifstream str2(ans.c_str());
string output,ac;
string tmp;
while(getline(str1,tmp))
output+=tmp+"\n";
str1.close();
while(getline(str2,tmp))
ac+=tmp+"\n";
str2.close();
if(output!=ac) return WA;
if(output==ac){
if(ed-st>(long long)sec) return TLE;
else return AC;
}
}
void PrintAC(){
cout<<" ### ###### \n ## ## ## ## \n ## ## ## \n## ## ## \n######### ## \n## ## ## ## \n## ## ###### \n";
return;
}
void PrintWA(){
cout<<"## ## ### \n## ## ## ## ## \n## ## ## ## ## \n## ## ## ## ## \n## ## ## ######### \n## ## ## ## ## \n ### ### ## ## \n";
return;
}
void PrintRE(){
cout<<"######## ######## \n## ## ## \n## ## ## \n######## ###### \n## ## ## \n## ## ## \n## ## ######## \n";
return;
}
void PrintTLE(){
cout<<"######## ## ######## \n ## ## ## \n ## ## ## \n ## ## ###### \n ## ## ## \n ## ## ## \n ## ######## ######## \n";
return;
}
void judge(string prg,string in,string out,string ans,int sec){
int ti;
int id=test(prg,in,out,ans,sec,ti);
cout<<"/************************"<<endl;
cout<<"Program: "<<prg<<endl;
cout<<"Input: "<<in<<endl;
cout<<"Output: "<<out<<endl;
cout<<"Answer: "<<ans<<endl;
cout<<"TimeLimit: "<<sec<<endl;
cout<<"RunningTime: "<<ti<<endl;
cout<<"Result: ";
if(id==AC) cout<<"AC\n",PrintAC();
if(id==WA) cout<<"WA\n",PrintWA();
if(id==TLE) cout<<"TLE\n",PrintTLE();
if(id==RE) cout<<"RE\n",PrintRE();
cout<<endl;
cout<<"************************/"<<endl;
}
int main(){
judge("example.exe","input.txt","output.txt","answer.txt",1);
return 0;
}将这段代码复制,并在 下编译,即可实现一个简单的单测试点评测机
结语
这只是一个简单的示例,还有很多有待改进的地方。
如:
- 计时器可以换成 chrono 中的时钟,这样可以测量更精准的时间
- 可以添加多测试点的评测功能
- 可以添加自动编译的功能,检查 CE