- C24zhuchengyu's blog
对拍程序
- @ 2025-6-4 17:18:06
#include <windows.h>
#include <string>
#include <stdexcept>
#include <bits/stdc++.h>
#include <string>
#include <stdexcept>
#ifdef _WIN32
#include <windows.h>
#else
#include <cstdio>
#include <memory>
#include <array>
#endif
std::string getans(const std::string& command) {
std::string result;
#ifdef _WIN32
// Windows实现
HANDLE hPipeRead, hPipeWrite;
SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES)};
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
if (!CreatePipe(&hPipeRead, &hPipeWrite, &sa, 0))
throw std::runtime_error("CreatePipe failed");
STARTUPINFOW si = {sizeof(STARTUPINFOW)};
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
si.hStdOutput = hPipeWrite;
si.hStdError = hPipeWrite;
si.wShowWindow = SW_HIDE;
PROCESS_INFORMATION pi = {0};
std::wstring wcommand(command.begin(), command.end());
if (!CreateProcessW(NULL, &wcommand[0], NULL, NULL, TRUE,
CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
{
CloseHandle(hPipeWrite);
CloseHandle(hPipeRead);
throw std::runtime_error("CreateProcess failed");
}
CloseHandle(hPipeWrite);
char buffer[4096];
DWORD bytesRead;
while (ReadFile(hPipeRead, buffer, sizeof(buffer), &bytesRead, NULL) && bytesRead) {
result.append(buffer, bytesRead);
}
CloseHandle(hPipeRead);
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
#else
// Linux/Unix实现
std::array<char, 128> buffer;
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(command.c_str(), "r"), pclose);
if (!pipe) {
throw std::runtime_error("popen() failed");
}
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
result += buffer.data();
}
#endif
return result;
}
#include<unistd.h>
using namespace std;
int main(){
string ft,lw;
cout<<"需要测试的代码:";
cin>>ft;
cout<<"输出正解的代码:";
cin>>lw;
string a1="g++.exe \""+ft+"\" -o "+"1.exe";
string a2="g++.exe \""+lw+"\" -o "+"2.exe";
cout<<"编译命令:\n"<<a1<<"\n"<<a2<<endl;
system(a1.c_str());
system(a2.c_str());
srand(time(0));
system("cls");
cout<<"开始测试";
Sleep(500);
cout<<".";
Sleep(500);
cout<<".";
Sleep(500);
cout<<".";
Sleep(500);
cout<<".";
Sleep(500);
cout<<".";
int k=1;
while(k){
system("cls");
int x1=rand()%1000,x2=x1+rand()%100000;
string t1="1.exe "+to_string(x1)+" "+to_string(x2),t2="2.exe "+to_string(x1)+" "+to_string(x2);
cout<<"命令:\n"<<t1<<"\n"<<t2<<endl;
string a=getans(t1),b=getans(t2);
if(a!=b){
cout<<"Break at:\n"<<x1<<" "<<x2<<"\n----------\nOutput1:\n"<<a<<"\n----------\nOutput2:\n"<<b;
break;
}
cout<<"成功次数:"<<k++;
}
}
修改行即可.