如何阻止 C++控制台应用程序立即退出吗?

发布于 2024-08-26 23:55:29 字数 170 浏览 7 评论 0原文

最近,我一直在尝试从这个网站学习C++。不幸的是,每当我尝试运行其中一个代码示例时,我都会看到该程序打开大约半秒,然后立即关闭。有没有办法阻止程序立即关闭,以便我可以看到我的努力的成果?

Lately, I've been trying to learn C++ from this website. Unfortunately whenever I try to run one of the code samples, I see that program open for about a half second and then immediately close. Is there a way to stop the program from closing immediately so that I can see the fruits of my effort?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

唔猫 2024-09-02 23:55:30

在代码末尾之前,插入以下行:

system("pause");

这将保留控制台,直到您按下某个键。

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s;
    cout << "Please enter your first name followed by a newline\n";
    cin >> s;
    cout << "Hello, " << s << '\n';
    system("pause"); // <----------------------------------
    return 0; // This return statement isn't necessary
}

Before the end of your code, insert this line:

system("pause");

This will keep the console until you hit a key.

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s;
    cout << "Please enter your first name followed by a newline\n";
    cin >> s;
    cout << "Hello, " << s << '\n';
    system("pause"); // <----------------------------------
    return 0; // This return statement isn't necessary
}
狼性发作 2024-09-02 23:55:30

调用 cin.get(); 2 次:

    //...
    cin.get();
    cin.get();
    return 0
}

Call cin.get(); 2 times:

    //...
    cin.get();
    cin.get();
    return 0
}
情归归情 2024-09-02 23:55:30

如果您从功能强大的 IDE 运行代码,例如 Code::Blocks,IDE 将管理控制台它用于运行代码,并在应用程序关闭时保持打开状态。您不想添加特殊代码来保持控制台打开,因为当您在 IDE 之外实际使用它时,这会阻止它正常运行。

If you run your code from a competent IDE, such as Code::Blocks, the IDE will manage the console it uses to run the code, keeping it open when the application closes. You don't want to add special code to keep the console open, because this will prevent it functioning correctly when you use it for real, outside of the IDE.

若相惜即相离 2024-09-02 23:55:30

我只是这样做:

//clear buffer, wait for input to close program
std::cin.clear(); std::cin.ignore(INT_MAX, '\n');
std::cin.get();
return 0;

注意:清除 cin 缓冲区,只有当您在程序早期的某个时刻使用过 cin 时才需要这样做。另外使用 std::numeric_limits::max() 可能比 INT_MAX 更好,但它有点啰嗦而且通常是不必要的。

I just do this:

//clear buffer, wait for input to close program
std::cin.clear(); std::cin.ignore(INT_MAX, '\n');
std::cin.get();
return 0;

Note: clearing the cin buffer and such is only necessary if you've used cin at some point earlier in your program. Also using std::numeric_limits::max() is probably better then INT_MAX, but it's a bit wordy and usually unnecessary.

缪败 2024-09-02 23:55:30

好吧,我猜你在 Windows 上使用 Visual Studio...为什么?因为如果您使用某种 Linux 操作系统,那么您可能会从控制台运行它。

无论如何,您可以像其他人建议的那样在程序末尾添加垃圾,或者您可以直接按 CTRL + F5 (启动而不调试),Visual Studio 将在完成后让控制台保持打开状态。

如果您想运行调试版本而不在代码中添加垃圾,另一个选择是打开控制台窗口(开始 -> 运行 -> cmd)并导航到您的调试输出目录。然后,只需输入可执行文件的名称,它将在控制台中运行您的调试程序。然后,如果您确实想要的话,您可以使用 Visual Studio 的附加到进程或其他东西。

Okay I'm guessing you are on Windows using Visual Studio... why? Well because if you are on some sort of Linux OS then you'd probably be running it from the console.

Anyways, you can add crap to the end of your program like others are suggesting, or you can just hit CTRL + F5 (start without debugging) and Visual Studio will leave the console up once complete.

Another option if you want to run the Debug version and not add crap to your code is to open the console window (Start -> Run -> cmd) and navigate to your Debug output directory. Then, just enter the name of your executable and it will run your debug program in the console. You can then use Visual Studio's attach to process or something if you really want to.

凉墨 2024-09-02 23:55:30

只需在程序末尾添加以下内容即可。它将尝试捕获某种形式的用户输入,从而阻止控制台自动关闭。

cin.get();

Just add the following at the end of your program. It will try to capture some form of user input thus it stops the console from closing automatically.

cin.get();
只有一腔孤勇 2024-09-02 23:55:30

如果您实际上是在 Visual C++ 中调试应用程序,请按 F5 或工具栏上的绿色三角形。如果您没有真正调试它(没有设置断点),请按 Ctrl+F5 或在菜单上选择“启动而不调试”(它通常位于“调试”菜单上,我同意这很令人困惑。)它会快一点,对您来说更重要的是,将在最后暂停,而无需更改代码。

或者,打开命令提示符,导航到 exe 所在的文件夹,然后输入其名称来运行它。这样,当运行完成时,命令提示符不会关闭,您可以看到输出。我更喜欢这两种方法,而不是添加在应用程序完成时停止的代码。

If you are actually debugging your application in Visual C++, press F5 or the green triangle on the toolbar. If you aren't really debugging it (you have no breakpoints set), press Ctrl+F5 or choose Start Without Debugging on the menus (it's usually on the Debug menu, which I agree is confusing.) It will be a little faster, and more importantly to you, will pause at the end without you having to change your code.

Alternatively, open a command prompt, navigate to the folder where your exe is, and run it by typing its name. That way when it's finished running the command prompt doesn't close and you can see the output. I prefer both of these methods to adding code that stops the app just as its finished.

坐在坟头思考人生 2024-09-02 23:55:30

在任何 exit() 函数之前或 main() 中的任何 return 之前添加以下行:

std::cout << "Paused, press ENTER to continue." << std::endl;
cin.ignore(100000, "\n");

Add the following lines before any exit() function or before any returns in main():

std::cout << "Paused, press ENTER to continue." << std::endl;
cin.ignore(100000, "\n");
魔法少女 2024-09-02 23:55:30

对于 Visual Studio(且仅 Visual Studio),以下代码片段为您提供“等待按键继续”提示,通过首先刷新输入缓冲区,真正等待用户显式按下键:

#include <cstdio>
#include <tchar.h>
#include <conio.h>

_tprintf(_T("Press a key to continue "));
while( _kbhit() /* defined in conio.h */ ) _gettch();
_gettch();

请注意,这使用 tchar.h 宏来与多个“字符集”(VC++ 如此称呼它们)兼容。

For Visual Studio (and only Visual Studio) the following code snippet gives you a 'wait for keypress to continue' prompt that truly waits for the user to press a new key explicitly, by first flushing the input buffer:

#include <cstdio>
#include <tchar.h>
#include <conio.h>

_tprintf(_T("Press a key to continue "));
while( _kbhit() /* defined in conio.h */ ) _gettch();
_gettch();

Note that this uses the tchar.h macro's to be compatible with multiple 'character sets' (as VC++ calls them).

魂ガ小子 2024-09-02 23:55:30

使用#include "stdafx.h" & system("pause"); 就像下面的代码一样。

#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
    std::cout << "hello programmer!\n\nEnter 2 numbers: ";
    int x, y;
    std::cin >> x >> y;
    int w = x*y;
    std::cout <<"\nyour answer is: "<< w << endl;
    system("pause");
}

Use #include "stdafx.h" & system("pause"); just like the code down below.

#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
    std::cout << "hello programmer!\n\nEnter 2 numbers: ";
    int x, y;
    std::cin >> x >> y;
    int w = x*y;
    std::cout <<"\nyour answer is: "<< w << endl;
    system("pause");
}
会发光的星星闪亮亮i 2024-09-02 23:55:30

yeh 答案类似的想法,只是极简主义的替代方案。

创建一个包含以下内容的批处理文件:

helloworld.exe
pause

然后使用该批处理文件。

Similar idea to yeh answer, just minimalist alternative.

Create a batch file with the following content:

helloworld.exe
pause

Then use the batch file.

银河中√捞星星 2024-09-02 23:55:30

只是

#include <cstdio>

    int main(){
        // code...
        std::getchar();
        std::getchar();
        return 0;
    }

由于某种原因,当您运行程序时,通常可以使用 stdin 中已有的 getchar 读取 1 个字符。因此第一个 getchar 读取该字符,第二个 getchar 在退出程序之前等待用户(您的)输入。程序退出后,大多数终端(尤其是 Windows)会立即关闭终端。
所以我们的目标是一种简单的方法来防止程序在输出所有内容后完成。
当然,还有更复杂、更简洁的方法来解决这个问题,但这是最简单的。

simply

#include <cstdio>

    int main(){
        // code...
        std::getchar();
        std::getchar();
        return 0;
    }

for some reason there is usually 1 character possible to read with getchar already in stdin when you run a program. so the first getchar reads this character, and the second getchar waits for user (your) input before exiting the program. And after a program exits most of terminals, especially on Windows close terminal immediately.
so what we aim to is a simple way of preventing a program from finishing after it outputs everything.
Of course there are more complex and clean ways to solve this, but this is the simplest.

灼疼热情 2024-09-02 23:55:30

查看您的 IDE 项目设置中是否有一个复选框,用于在程序终止后保持窗口打开。如果没有,请使用 std::cin.get(); 在 main 函数末尾读取一个字符。但是,请确保仅使用基于行的输入(std::getline)或处理剩余的未读字符(std::忽略直到换行),因为否则最后的 .get() 只会读取您留下的垃圾之前未读过。

See if your IDE has a checkbox in project setting to keep the window open after the program terminates. If not, use std::cin.get(); to read a character at the end of main function. However, be sure to use only line-based input (std::getline) or to deal with leftover unread characters otherwise (std::ignore until newline) because otherwise the .get() at the end will only read the garbage you left unread earlier.

萌逼全场 2024-09-02 23:55:30

这似乎运作良好:

cin.clear();
cin.ignore(2);

如果您先清除缓冲区,那么当您读取下一个缓冲区时就不会出现问题。
由于某种原因 cin.ignore(1) 不起作用,它必须是 2。

This seems to work well:

cin.clear();
cin.ignore(2);

If you clear the buffer first it won't be a problem when you read the next one.
For some reason cin.ignore(1) does not work, it has to be 2.

她如夕阳 2024-09-02 23:55:30

您始终可以创建一个批处理文件。例如,如果您的程序名为 helloworld.exe,则某些代码将是:

@echo off
:1
cls
call helloworld.exe
pause >nul
goto :1

You could always just create a batch file. For example, if your program is called helloworld.exe, some code would be:

@echo off
:1
cls
call helloworld.exe
pause >nul
goto :1
空‖城人不在 2024-09-02 23:55:30

如果您运行的是 Windows,则可以执行 system("pause >nul");system("pause");。它执行控制台命令来暂停程序,直到您按下某个键。 >nul 阻止它显示 Press any key to continue...

If you are running Windows, then you can do system("pause >nul"); or system("pause");. It executes a console command to pause the program until you press a key. >nul prevents it from saying Press any key to continue....

新人笑 2024-09-02 23:55:30

我在程序的最后一个 return 0 处放置了一个断点。效果很好。

I'm putting a breakpoint at the last return 0 of the program. It works fine.

皓月长歌 2024-09-02 23:55:30

我使用了 cin.get() ,这是有效的,但有一天我需要在此之前使用另一个 cin.get([Array Variable]) 来获取一个 ling 字符串中间有空白字符。因此 cin.get() 并没有避免命令提示符窗口关闭。最后我找到了另一种方法:
CTRL+F5 在外部窗口中打开,Visual Studio 不再对其进行控制。只是会在最终命令运行后询问您有关关闭的问题。

I used cin.get() and that is worked but one day I needed to use another cin.get([Array Variable]) before that to grab a ling string with blank character in middle of. so the cin.get() didn't avoid command prompt window from closing. Finally I found Another way:
Press CTRL+F5 to open in an external window and Visual Studio does not have control over it anymore. Just will ask you about closing after final commands run.

神也荒唐 2024-09-02 23:55:30

我尝试在末尾添加一个 getchar() 函数。但这没有用。所以我所做的就是依次添加两个 getchar() 函数。我认为第一个 getchar() 吸收了您在最后一次数据输入后按下的 Enter 键。因此,请尝试添加两个 getchar() 函数,而不是一个

I tried putting a getchar() function at the end. But it didn't work. So what I did was add two getchar() functions one after another. I think the first getchar() absorbs the Enter key you press after the last data input. So try adding two getchar() functions instead of one

荒岛晴空 2024-09-02 23:55:30

不要按运行按钮,而是同时按 CTRL 和 F5,它会给您按任意键继续消息。或者在主函数末尾输入“(警告仅用于测试非实际程序,因为防病毒软件不喜欢它!!!!)”,但是:(警告仅用于测试非实际程序,因为防病毒软件不喜欢它不喜欢!!!!)

Instead of pressing the run button, press CTRL and F5 at the same time, it will give you the press any key to continue message. Or type "(warning use this only for testing not actual programs as an antiviruses don't like it!!!!)" at the end of your main function but: (warning use this only for testing not actual programs as an antiviruses don't like it!!!!)

那片花海 2024-09-02 23:55:30

只需在 return 0 之前使用 cin.ignore() 即可;两次

main()
  {
  //your codes 

  cin.ignore();
  cin.ignore();

  return 0;
  }

就够了

just use cin.ignore() right before return 0; twice

main()
  {
  //your codes 

  cin.ignore();
  cin.ignore();

  return 0;
  }

thats all

記柔刀 2024-09-02 23:55:30

您也可以尝试这样做,

sleep (50000);
cout << "any text" << endl;

这会将您的代码保存 50000m,然后打印消息并关闭。但请记住,它不会永远暂停。

you can try also doing this

sleep (50000);
cout << "any text" << endl;

This will hold your code for 50000m, then prints message and closes. But please keep in mind that it will not pause forever.

世态炎凉 2024-09-02 23:55:30

这里有一个问题,不是那么明显。不知何故,我在程序的最后一行添加了一个调试断点。 } 不确定我是如何做到的,可能是在不同屏幕之间跳转时错误地单击了鼠标。我在 VS Code 工作。

当我去调试时,系统立即跳转到该断点。没有错误消息,没有临时输出,什么也没有。我想,程序是如何冲过我设置的所有断点的?这花了太长时间才弄清楚。

显然,系统将最后一行断点视为“第一个”停止点。简单的修复方法?删除那个断点,哦! (此处插入拍额头。)

Here's a problem, not so obvious. Somehow I had added a debug breakpoint at the very last line of my program. } Not sure how I did that, perhaps with an erroneous mouse click while jumping between different screens. I'm working in VS Code.

And when I go to debug, the system jumps immediately to that breakpoint. No error message, no interim output, nothing. I'm like, how did the program rush thru all my set breakpoints? This took too long to figure out.

Apparently the system sees that last line breakpoint as a "first" stop. The simple fix? Delete that breakpoint, doh! (insert forehead slap here.)

小霸王臭丫头 2024-09-02 23:55:30

在我为 OpenCV C++ 开发设置 Visual Studio 后,我遇到了这个问题(更像是一个功能而不是问题)。我必须启用控制台的自动关闭。当运行在控制台中返回输出的普通 C++ 程序时,它会立即关闭。
我在另一个问题中找到了解决方案并且有效:

https://stackoverflow.com/a/54084067/15012520

转到工具>>选项>>调试>>一般>>调试停止时自动关闭控制台。

I ran across this problem(more like a feature and not a problem) after I setup visual studio for OpenCV C++ development. I must have enabled automatic closing of the console. When running normal C++ programs that return an output in the console it closed instantly.
I found a solution in another question and it worked:

https://stackoverflow.com/a/54084067/15012520

Go to Tools >> Options >> Debugging >> General >> Automatically close the console when debugging stops.

剩一世无双 2024-09-02 23:55:29

如果您使用的是 Visual Studio 并且要从 IDE 启动控制台应用程序:

CTRL-F5(启动但不进行调试)将启动应用程序并保持控制台窗口打开,直到您按任意键。

If you are using Visual Studio and you are starting the console application out of the IDE:

pressing CTRL-F5 (start without debugging) will start the application and keep the console window open until you press any key.

别闹i 2024-09-02 23:55:29

编辑: 正如 Charles Bailey 在下面的评论中正确指出的那样,如果 stdin 中缓冲了字符,这将不起作用,并且确实没有好的方法来解决这个问题。如果您在附加调试器的情况下运行,约翰·迪布林(John Dibling)建议的解决方案可能是解决您问题的最干净的解决方案。

也就是说,我将把它留在这里,也许其他人会发现它有用。在开发过程中编写测试时,我经常使用它作为一种快速技巧。


main 函数末尾,您可以调用 < code>std::getchar();

这将从 stdin 获取单个字符,从而为您提供“按任意键继续”的行为(如果您实际上想要一条“按任意键”消息,您必须自己打印一条)。

对于 getchar,您需要 #include

Edit: As Charles Bailey rightly points out in a comment below, this won't work if there are characters buffered in stdin, and there's really no good way to work around that. If you're running with a debugger attached, John Dibling's suggested solution is probably the cleanest solution to your problem.

That said, I'll leave this here and maybe someone else will find it useful. I've used it a lot as a quick hack of sorts when writing tests during development.


At the end of your main function, you can call std::getchar();

This will get a single character from stdin, thus giving you the "press any key to continue" sort of behavior (if you actually want a "press any key" message, you'll have to print one yourself).

You need to #include <cstdio> for getchar.

诠释孤独 2024-09-02 23:55:29

James 的解决方案适用于所有平台。

或者,在 Windows 上,您还可以在从 main 函数返回之前添加以下内容:

  system("pause");

这将运行 pause 命令,该命令会等待您按下 a键并显示一条友好消息 Press any key to continue 。 。 .

The solution by James works for all Platforms.

Alternatively on Windows you can also add the following just before you return from main function:

  system("pause");

This will run the pause command which waits till you press a key and also displays a nice message Press any key to continue . . .

勿挽旧人 2024-09-02 23:55:29

如果您使用 Microsoft 的 Visual C++ 2010 Express 并遇到 CTRL+F5 在程序终止后无法保持控制台打开的问题,请查看 此 MSDN 线程

可能您的 IDE 设置为在 CTRL+F5 运行后关闭控制台;事实上,Visual C++ 2010 中的“空项目”默认会关闭控制台。要更改此设置,请按照 Microsoft 版主的建议进行操作:

请右键单击您的项目名称并转到“属性”页面,请展开“配置属性”->“链接器->系统,请在子系统下拉列表中选择控制台(/SUBSYSTEM:CONSOLE)。因为,默认情况下,Empty 项目没有指定它。

If you are using Microsoft's Visual C++ 2010 Express and run into the issue with CTRL+F5 not working for keeping the console open after the program has terminated, take a look at this MSDN thread.

Likely your IDE is set to close the console after a CTRL+F5 run; in fact, an "Empty Project" in Visual C++ 2010 closes the console by default. To change this, do as the Microsoft Moderator suggested:

Please right click your project name and go to Properties page, please expand Configuration Properties -> Linker -> System, please select Console (/SUBSYSTEM:CONSOLE) in SubSystem dropdown. Because, by default, the Empty project does not specify it.

A君 2024-09-02 23:55:29

我通常只是在 main() 的右花括号上放置一个断点。当通过任何方式到达程序末尾时,断点都会命中,您可以按 ALT-Tab 切换到控制台窗口来查看输出。

I usually just put a breakpoint on main()'s closing curly brace. When the end of the program is reached by whatever means the breakpoint will hit and you can ALT-Tab to the console window to view the output.

表情可笑 2024-09-02 23:55:29

为什么不直接从控制台运行该程序,即如果您使用的是 Windows,则从 cmd.exe 运行该程序。这样,程序完成后窗口将保持打开状态。

[编辑]:当我使用 KDevelop4 时,IDE 底部的选项卡中运行着一个成熟的 Bash(Linux CLI)实例。这就是我在这种情况下使用的。

Why not just run the program from a console ie run the program from cmd.exe if you're using Windows. That way the window stays open after the program finishes.

[EDIT]: When I use KDevelop4 there is a fully fledged instance of Bash (a Linux CLI) running in a tab at the bottom of the IDE. Which is what I use in these sort of circumstances.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文