如何使 windows 命令提示符在C++可执行文件上显示返回值?
How to make the windows command prompt show the return value on a C++ executable?
我正在使用 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
请注意,我们全局使用了变量i
atexit()
因为传递的函数必须返回 void(即什么都没有(,这就是在用户定义的函数中不传递i
的原因onExit()
而不是别的。
atexit()
的定义如下:
extern "C++" int atexit (void (*func)(void)) noexcept;
相关文章:
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- 从python中调用C++函数并获取返回值
- 为什么模板类中的对象不能返回值
- 返回值优化:显式移动还是隐式
- lock_guard是否保护返回值
- 调用CreateProcess()并获取字符串的返回值
- 如何使 windows 命令提示符在C++可执行文件上显示返回值?
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 查找 GCD:并非所有控制路径都返回值
- 在 Arduino 上使用 sscanf 会导致与 const char * 不匹配,并且返回值始终相同,尽管输入值不同
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 如何从 std::thread 返回值
- 将返回值从 exe 传递到 bat,并将其传递给 C# 中的进程
- 显示C++输出而不返回值
- 函数不显示返回值 - C++
- 函数不返回值,但 cout 显示它
- 可视化C++调试器未显示返回值
- int main() 的返回值是什么意思,如何显示它?
- C++返回值显示为-858993460
- Visio & UML - 在属性和返回值中显示指针