如何使用 C++ 读取另一个程序中源代码的输出

How to read output of source code in another program with C++

我觉得这真的很难解释我想要什么。但是,让我试试。 (我正在尝试构建一个程序 用于评分 学生的编程作业)

C++中有很多简单的源代码。 (请想想有100多个代码文件

// C:\homework1\studentA.cpp
int main()
{
    cout << "The answer is 456" << endl;
}

这是问题。大家可以看到,代码文件一大堆,我没法编译,一个一个检查对不对。所以,为了方便起见,我需要制作评分程序。

如何在另一个程序中读取标准输出(答案是 456)? 'compiling source code' 和 'save standard output' 有什么功能吗?

我会为此使用 bash 脚本而不是 C++。大致如下:

g++ $filename
./a.out > student_answer.txt
diff -q student_answer.txt expected_answer.txt

然后,$?会告诉你答案是否正确。

How can I read the standard output (The answer is 456) in another program?

如果没有 operating system. Because you don't have (in general, according to the C++17 standard) some "other program" running (read about processes). When you have one, please thank your OS. Read some textbook about operating systems 的帮助,您无法做到这一点。

但是,在 Linux 上,您可以只使用 popen(3) (or fork(2), execve(2), pipe(7) so pipe(2), dup2(2), waitpid(2)) and on operating systems for which Qt has been ported (that includes Windows, but read about the WinAPI), you could use QProcess

如果您有疑虑,请考虑在 Linux 上使用 setuid and/or chroot techniques (perhaps with LXC) 以提高您工具的安全性。

另请查看 POCO 框架库。