如何确保运行代码时控制台不会立即关闭? [英] How to make sure console doesn't close immediately when running code?
问题描述
我正在尝试学习C编程,但是当我运行我的cmd代码时,窗口立即关闭,而没有给我任何更改来查看程序是否打印了我想要的结果。
I'm trying to learn C programming, but when I run my code the cmd, window closes immediately, without giving me the change to see if the program printed the result I was aiming for.
我正在VS-Code上使用几个扩展名对C进行编码。是否有设置/扩展名/代码段,或者我能立即关闭的任何内容?
I'm coding C on VS-Code, using several extensions. Is there a setting/extension/code snippet, or anything I can do so it won't close immediately?
谢谢!
推荐答案
最简单(也是最常见)的方法是添加 system( pause);
在 main
函数中的返回0;
语句之前紧接:
The easiest (and most common) way to do this is to add the line system("pause");
immediately before the return 0;
statement in your main
function:
#include <stdio.h>
#include <stdlib.h> // This header defines the "system()" function
// For C++ builds, #include <iostream> will suffice
int main()
{
printf("Hello, World!\n");
system("pause");
return 0;
}
此调用将产生提示并等待用户的按键操作。显示的确切消息可能因编译器和/或平台而异,但是,对于Visual Studio和 MSVC
,该消息为:
This call will produce a prompt and await a key-press from the user. The exact message displayed may vary between compilers and/or platforms but, with Visual Studio and MSVC
, the message is:
按任意键继续。 。 。
Press any key to continue . . .
这篇关于如何确保运行代码时控制台不会立即关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!