如何使 windows 命令提示符在C++可执行文件上显示返回值?

How to make the windows command prompt show the return value on a C++ executable?

本文关键字:显示 返回值 可执行文件 C++ 何使 windows 命令提示符      更新时间:2023-10-16

我正在使用 Dev C++ 编写 c++(用于竞争性编程,已经做了几个月(,但过了一段时间我决定尝试在 VSCode 上做(顺便说一句,这个可怕的想法(。一切都最终工作了,但是当通过 Dev 在命令提示符下执行程序时,C++它显示了 main 函数的执行时间和返回值,如下所示:

Process exited after 4.962 seconds with return value 0

问题是,当通过正常方式执行c ++ .exe文件时,这些东西没有显示出来,我什至不知道它来自哪里。是否有程序或命令使这些显示在命令提示符上?

编辑:该评论解决了我的问题 "Windows不会跟踪执行时间。回显 %错误级别% 打印退出代码。

实现要求的非常粗略的示例:

#include <iostream>
// to count time elapsed from beginning to end of the program
#include <chrono>
// for atexit() function
#include <cstdlib>
using namespace std::chrono;
// used globally, see the reason below of the answer
int i;
void onExit();
int main(void) {
int input;
// clock begins
steady_clock::time_point begin = steady_clock::now();
// --- SOME LONG PROGRAM ---
std::cin >> input;
// clock ends    
steady_clock::time_point end = steady_clock::now();
// calculating the difference
long long diff = duration_cast<milliseconds>(end - begin).count();
// displaying the time    
std::cout << "Process exited in " << diff / 1000.00 << 's' << std::endl;
// on exit of the program, this function will be executed
atexit(&onExit);
// supposing the return code is 5
i = 5;
return i;
}
// exit function to be executed before exit    
void onExit() {
std::cout << "Exit code: " << i << std::endl;
}

这将输出如下内容:

test     // --- INPUT
Process exited in 4.383s
Exit code: 5

请注意,我们全局使用了变量iatexit()因为传递的函数必须返回 void(即什么都没有(,这就是在用户定义的函数中不传递i的原因onExit()而不是别的。

atexit()的定义如下:

extern "C++" int atexit (void (*func)(void)) noexcept;