- 分享
内容由AI生成
- @ 2026-7-21 10:20:08
#include #include #include #include using namespace std;
int main() { cout << "========== C++ 代码执行器 ==========" << endl; cout << "请输入 C++ 代码,最后一行输入 END 结束输入:" << endl; cout << endl;
// 打开临时文件写入用户代码
ofstream codeFile("temp_user_code.cpp");
if (!codeFile.is_open()) {
cout << "错误:无法创建临时文件!" << endl;
return 1;
}
string line;
while (true) {
getline(cin, line);
if (line == "END") {
break;
}
codeFile << line << endl;
}
codeFile.close();
cout << endl;
cout << "正在编译 temp_user_code.cpp ..." << endl;
// 编译用户代码
string compileCmd = "g++ -std=c++14 temp_user_code.cpp -o temp_user_code.exe 2>compile_error.txt";
int compileResult = system(compileCmd.c_str());
// 检查是否有编译错误
ifstream errorFile("compile_error.txt");
bool hasError = false;
string errorContent = "";
string errorLine;
while (getline(errorFile, errorLine)) {
if (!errorLine.empty()) {
hasError = true;
errorContent += errorLine + "\n";
}
}
errorFile.close();
if (compileResult != 0 || hasError) {
cout << endl;
cout << "===== 编译失败 =====" << endl;
cout << errorContent;
cout << "=====================" << endl;
remove("temp_user_code.cpp");
remove("compile_error.txt");
return 1;
}
cout << "编译成功!" << endl;
cout << endl;
cout << "===== 运行结果 =====" << endl;
// 运行编译好的程序
int runResult = system("temp_user_code.exe");
cout << "=====================" << endl;
cout << endl;
if (runResult == 0) {
cout << "程序运行成功,返回值:0" << endl;
} else {
cout << "程序运行出错,返回值:" << runResult << endl;
}
// 清理临时文件
remove("temp_user_code.cpp");
remove("temp_user_code.exe");
remove("compile_error.txt");
cout << endl;
system("pause");
return 0;
}
1 条评论
-
吴肖宇 LV 3 @ 2026-7-21 10:27:22先复制(Ctrl+c),再在黑框中粘贴(Ctrl+v)代码
- 1