跳到正文

科技·工程

简易评测机

原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年8月5日
篇幅
约 5 分钟

版本

  1. v1当前

如何自制一个评测机

大家都知道 OJ 评测程序的时候,输入都是从文件中读取的, 但我们平时写程序的时候都是用 STDIO 进行输入输出的。那如何在不改变程序的前提下,重定向输入输出呢?

这时候命令行工具就派上用场了。

在C++中有个函数叫做 system,返回值是一个 int,也就是命令执行完成后返回的错误码。

下面只讨论 windows 的命令行 cmd。

除此以外 cmd 还支持管道操作符|

所以我们可以用这样一行 cmd 命令完成输入输出

代码
type in.txt | example.exe > out.txt

代码示例

C++
#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;
}

将这段代码复制,并在 windows \color{red} windows 下编译,即可实现一个简单的单测试点评测机

结语

这只是一个简单的示例,还有很多有待改进的地方。

如:

  • 计时器可以换成 chrono 中的时钟,这样可以测量更精准的时间
  • 可以添加多测试点的评测功能
  • 可以添加自动编译的功能,检查 CE
原文