Как в visual studio оставить консоль
Я начинаю в Visual C++ , и я хотел бы знать, как сохранить окно консоли.
например, это будет типичное приложение "hello world":
какую строку я пропускаю?
начните проект с Сочетание Клавиш Ctrl+Клавишу F5 вместо Ф5 .
обратите внимание, что для этого требуется Console (/SUBSYSTEM:CONSOLE) опция компоновщика, которую вы можете включить следующим образом:
- откройте проект и перейдите в Обозреватель решений. Если вы следуете вместе со мной в K&R, ваше "решение" будет "Привет" с 1 проектом под ним, а также "привет" в смелый.
- щелкните правой кнопкой мыши на" hello " (или как бы ни назывался ваш проект.)
- выберите "Свойства"в контекстном меню.
- Выберите Свойства Конфигурации>Компоновщик>Система.
- для свойства "подсистема"в правой области щелкните раскрывающийся список в правом столбце.
- выберите " консоль (/подсистема: консоль)"
- нажмите "Применить", дождитесь завершения работы, затем нажмите "ОК". (Если "применить" выделено серым цветом, выберите другой параметр подсистемы, нажмите кнопку Применить, затем вернитесь и примените параметр консоли. Мой опыт показывает, что OK сам по себе не будет работать.)
CTRL-F5 и подсказки подсистемы работают вместе; они не являются отдельными параметрами.
стандартный путь cin.get() перед вашим оператором return.
поставить точку останова на return линии.
вы запускаете его в отладчике, верно?
хотя это не очень портативный, потому что он будет работать только на Windows, но он будет автоматически печатать
нажмите любую клавишу для продолжения.
для проектов makefile принятое решение не выполняется из - за ошибки в Visual Studio (которая присутствует по крайней мере до версии 2012-я еще не тестировал 2013). Эта ошибка подробно здесь.
чтобы приостановить работу консоли после завершения программы в проекте makefile, выполните следующие действия (это может отличаться для версий, отличных от 2010 - 2012):
1) Pass /SUBSYSTEM:CONSOLE компоновщику. - редактировать: см под.
2) Откройте файл проекта (.vcxproj) в текстовом редакторе.
3) Внутри корневой тег, вставить следующее:
4) перезагрузите проект в своем решении.
5) запустите программу без отладки (CTRL + F5).
EDIT:
согласно моему комментарию ниже, установка опции компоновщика /SUBSYSTEM:CONSOLE на самом деле не имеет значения для проектов Makefile (и не обязательно даже возможно, если вы используете компилятор, отличный от MSVC). Все дело в том, что параметр добавляется .файл vcxproj, согласно шагу 3 выше.
можно использовать cin.get(); или cin.ignore(); непосредственно перед инструкцией return, чтобы избежать закрытия окна консоли.
просто добавьте точку останова в закрывающую скобку вашего _tmain метод. Это более простой способ плюс вам не нужно добавлять код для отладки.
просто поставьте точку останова на последней фигурной скобке main.
поместите точку останова на конец скобки main() . Он будет получить споткнулся даже с несколькими return заявления. Единственным недостатком является то, что вызов exit() не будет пойман.
Если вы не отлаживаете, следуйте советам в ответе Зойдберга и начните свою программу с Ctrl + Ф5 просто Ф5 .
cin.get (), или system("PAUSE"). Я не слышал, что вы можете использовать return (0);
была та же проблема . Я использую _getch () непосредственно перед оператором return. Это работает.
у меня была та же проблема; в моем приложении есть несколько точек выхода (), и не было никакого способа узнать, где именно он выходит, тогда я узнал об этом:
таким образом, он остановится независимо от того, где мы выходим из программы.
выбор 1: добавьте точку останова в конце main()
выбор 2: Добавьте этот код перед return 0; :
(некоторые опции могут быть вызваны разными именами. Я не использую английскую версию)
У меня была такая же проблема, когда я создавал проекты с опцией "пустой проект", создавал проект как "Win32-консольное приложение" вместо "пустой проект" . В появившемся диалоговом окне вы нажимаете "Продолжить", после чего можете проверить опцию" пустой проект "и нажать "подтвердить". После этого CTRL + F5 откроет консоль, которая не закрывается автоматически.
можно просто поставить keep_window_open (); перед возвращением вот один пример
просто добавьте систему ("пауза") в конце кода перед возвращением 0, как это
на самом деле, реальным решением является выбор самого шаблона проекта. Необходимо выбрать консольное приложение Win32 в старой версии VS или сначала заполнить имя проекта, а затем дважды щелкните мастер рабочего стола Windows и выберите консольное приложение Win32. Затем выберите пустой проект на этом этапе. Это затем позволяет то, что оригинальный спрашивающий действительно хотел без добавления дополнительной точки остановки и удерживайте код. Я тоже прошел через эту проблему. Ответ также находится в MSDN сайт.
вот способ сохранить окно команды открытым независимо от того, как выполнение останавливается без изменения кода:
на команда, enter $(ComSpec)
на Аргументы Командной Строки, enter /k $(TargetPath) . Добавьте любые аргументы в собственное приложение.
теперь Ф5 или Сочетания Клавиш Ctrl-Клавишу F5 выполняет Windows / System32 / cmd.exe в новом окне, и / k гарантирует, что командная строка остается открытой после завершения обработки.
недостатком является то, что выполнение не останавливается на точках останова.
When doing a console application in Java with Eclipse, I see the output being put in a text box in the IDE itself, instead of having a console popping up like in Visual Studio. This comes in handy, as even after the program has exited, I can still make good use of the text that was written in it, as it doesn't get erased until I run it again. Is it possible to achieve anything like that with Visual Studio? I know that instead of doing
but it is not quite the same thing, as you get a lot of "junk" in the Output window, as all the loaded symbols and such.
Even better, is it possible to have everything done in the IDE itself, when you run your application, instead of having the console running?
12 Answers 12
In the Tools -> Visual Studio Options Dialog -> Debugging -> Check the "Redirect All Output Window Text to the Immediate Window".
I've checked this checkbox but I still get a Console popup and nothing in the "Output" window (Debug, Test, Build. ) or the "Immediate Window".
@EvenLisle you need to change the application type to Windows Application as in stolsvik's answer. The option mentioned in this answer was on by default for me in any case.
What does "Redirect All Output Window Text to the Immediate Window" excactly mean? Use various contexts if you need to. I am confused by what is the "immediate window".
@TooTone The question clearly states for a "console application" and changing it to something else just for debugging purposes, where I cannot even Console.ReadKey() is just straight up ridiculous!
In the Visual Studio Options Dialog -> Debugging -> Check the "Redirect All Output Window Text to the Immediate Window". Then go to your project settings and change the type from "Console Application" to "Windows Application". At that point Visual Studio does not open up a console window anymore, and the output is redirected to the Output window in Visual Studio. However, you cannot do anything "creative", like requesting key or text input, or clearing the console - you'll get runtime exceptions.
I find this particularly clumsy. What, I wonder, is the rationale behind this in VS? It should be the ability of all modern day IDE's to have a panel within the IDE itself behave as the console for input and output. (scratches head)
The question clearly states for a "console application" and changing it to something else just for debugging purposes, where I cannot even Console.ReadKey() is just straight up ridiculous!
Not sure why but when I tried to revert the Output type of my application back from Windows Application to Console then the console window is no where to be seen when I run my application. I'm able to debug the application and Main entry point is also getting hit. I also reverted the option setting mentioned in this post but to no avail. I'm using VS 2017 community edition. I lost my console window (sobbing).
For what it's worth, in VS 15.8.7 the only way I could get the output to redirect for a console app was to change it to a Windows app, and leave the Redirect box UNCHECKED. If I check the box, it does not display the output.
Depending on what listeners you attach, trace output can go to the debug window, the console, a file, database, or all at once. The possibilities are literally endless, as implementing your own TraceListener is extremely simple.
Yes, but what I want to know is if it is possible to just do it, without having to implement it by myself.
@devoured The Trace class outputs just to the debug window by default. You only need to attach extra listeners (and there are several already written you can use) if you want to also see the output elsewhere.
I went to my Debug Options dialog and chose "Redirect all Output Window text to the Immediate Window" to make the Trace output go to the Immediate window so it doesn't get all mixed up with the debug crap.
It's time to check the latest release/s for Visual Studio, folks. The most suggested solution that did not work for some of you before might work now.
In Visual Studio 2017 (Release Version 15.4.2 and above), going to Tools > Options > Debugging > General > (Check Box) Redirect all Output Window text to Immediate Window has worked for me.
- To see the Immediate Window, make sure that you are in Debugging mode.
- There should now be 3 other debugging tools available at your disposal, namely, Call Stack, Breakpoints, and Command Window, as shown below:
Doublecheck that the project you're testing with was created as a "console application", not a "windows application". Your approach works with a windows application, but that's not what the OP specified.
You could create a wrapper application that you run instead of directly running your real app. The wrapper application can listen to stdout and redirect everything to Trace. Then change the run settings to launch your wrapper and pass in the path to the real app to run.
You could also have the wrapper auto-attach the debugger to the new process if a debugger is attached to the wrapper.
You can try VSConsole which allow you to integrate its console window inside VisualStudio as dock panel at bottom. To use this you have to
- Add VSCodeExtension to VisualStudio
- Add VSCode NugetPackage reference in your project.
- Add using Console = VSConsole.Console; as namespace reference in *.cs file
- change the Output type from Console Application to Windows Application to hide the main console window that pops up when you run your console application.
Then your application will use VSConsole.Console class insted of System.Console class.
I know this is just another answer, but I thought I'd write something down for the new Web Developers, who might get confused about the "Change to a Windows Application" part, because I think by default an MVC application in Visual Studio 2013 defaults to an Output Type of Class Library.
My Web Application by default is set as an output type of "Class Library." You don't have to change that. All I had to do was follow the suggestions of going to Tools > Options > Debugging > Redirect all Output Window text to the Immediate Window. I then used the System.Diagnostics.Trace suggestion by Joel Coehoorn above.
Instead, you can collect the output in a test result.
You can't supply input, but you can easily provide several tests with different command line arguments, each test collecting the output.
If your goal is debugging, this is a low effort way of offering a repeatable debugging scenario.
regarding System.Diagnostics.Debug producing a lot of "junk" in the Output window: You can turn that off by right clicking in the output window. E.g. there's an item "Module Load Messages" which you want to disable and an item "Program Output" which you want to keep.
You have three possibilities to do this, but it's not trivial. The main idea of all IDEs is that all of them are the parents of the child (debug) processes. In this case, it is possible to manipulate with standard input, output and error handler. So IDEs start child applications and redirect out into the internal output window. I know about one more possibility, but it will come in future
If you need output from Console.WriteLine, and the Redirect All Output Window Text to the Immediate Window does not function and you need to know the output of Tests from the Integrated Test Explorer, using NUnit.Framework our problem is already solved at VS 2017:
When we click on Blue Output, under Elapsed Time, at right, and it produces this:
Standard Output is our desired Output, produced by Console.WriteLine.
It functions for Console and for Windows Form Applications at VS 2017, but only for Output generated for Test Explorer at Debug or Run; anyway, this is my main need of Console.WriteLine output.
I'm starting out in Visual C++ and I'd like to know how to keep the console window.
For instance this would be a typical "hello world" application:
What's the line I'm missing?
The downside to all proposed solutions is that none of them work with debugging (Ctrl+F5 fails here) and when the application stops unexpectedly (all breakpoints or reads from stdin at main return fail here). What I would love to see is an in-IDE console window like Eclipse and other IDEs have. They simply keep showing the output to stdout/stderr after the program has terminated.
@sybren The accepted answer works with CTRL+F5, and why would you want a solution which works with debugging (F5)? Surely the whole point of debugging is to .. debug? What is the benefit of having a paused console after program termination, in a debugging session?
@JBentley Eclipse and other IDEs allow you read your program's output even after the process was terminated. Surely you see the added benefit, especially when trying to find a bug? Also a breakpoint only works when you know where the program is terminating, which can be hard to tell when the output disappears from your screen.
22 Answers 22
Start the project with Ctrl + F5 instead of just F5 .
The console window will now stay open with the Press any key to continue . . . message after the program exits.
Note that this requires the Console (/SUBSYSTEM:CONSOLE) linker option, which you can enable as follows:
- Open up your project, and go to the Solution Explorer. If you're following along with me in K&R, your "Solution" will be 'hello' with 1 project under it, also 'hello' in bold.
- Right click on the 'hello" (or whatever your project name is.)
- Choose "Properties" from the context menu.
- Choose Configuration Properties>Linker>System.
- For the "Subsystem" property in the right-hand pane, click the drop-down box in the right hand column.
- Choose "Console (/SUBSYSTEM:CONSOLE)"
- Click Apply, wait for it to finish doing whatever it does, then click OK. (If "Apply" is grayed out, choose some other subsystem option, click Apply, then go back and apply the console option. My experience is that OK by itself won't work.)
CTRL-F5 and the subsystem hints work together; they are not separate options.
This runs the program without debugging; it's better to have a solution that works in both debug and ordinary run mode.
For anyone who cannot get this solution to work in a makefile project, this is due to a bug in Visual Studio. I've just posted an answer with the fix.
Can confirm! Had a console app that didn't work did this and it worked. You do not need to change your code with cin.get(),getchar(), system("pause") or any other garbage. Changing this works.
Ctrl+F5 means 'Start Without Debugging'. So you can't use this when debugging. Just add system("pause"); in the end of your code. It makes sense and works fine.
The standard way is cin.get() before your return statement.
-1 for _tmain . I'd vote another -1 for the cin.get() instead of placing a breakpoint for F5 or using Ctrl F5. But I'm only allowed one downvote.
@Cheers: What is wrong with _tmain ? That's the standard way to write a Windows application targeting the Console subsystem. Deviating from that standard is what would be bad practice. Clearly, no one is talking about portable code here; the question says Visual C++ and _tmain is the signature that appears in the sample code. It's time to give up this religion. Windows is "non-standard" by default, and there are very good reasons for following its standards.
@CodyGray: My downvote for _tmain is because it is totally unnecessary non-standard (the international C++ standard requires a plain main ), and because it uses Microsoft's T macro scheme, which is needless complication and verbiage for supporting Windows 9x. If you feel deviating from the standard is bad practice, then you should absolutely not use tmain . There are no good reasons for using tmain , except for trolling or, for professionals, for displaying one's total incompetence.
Put a breakpoint on the return line.
You are running it in the debugger, right?
Another option is to use
Though this is not very portable because it will only work on Windows, but it will automatically print
system("pause") Will keep your processor running, it should not be used. Use a cin.get() or equivalent.
@Krythic I just tried it and it did not eat 100% CPU. My processor use was at 0% - 1% the whole time. Cannot reproduce.
system("pause") will call the "pause" command in cmd, which does NOT use the CPU all the time. It's equivalent to _getche() essentially.
For makefile projects, the accepted solution fails, due to a bug in Visual Studio (which is present at least up until version 2012 - I haven't yet tested 2013). This bug is detailed here.
In order to have the console pause after program termination on a makefile project, perform these steps (this may differ for versions other than 2010 - 2012):
1) Pass /SUBSYSTEM:CONSOLE to the linker. - EDIT: see below.
2) Open your project file (.vcxproj) in a text editor.
3) Inside the root tag, insert the following:
4) Reload the project in your solution.
5) Run the program without debugging (CTRL + F5).
EDIT:
As per my comment below, setting the linker option /SUBSYSTEM:CONSOLE is actually irrelevant for makefile projects (and not necessarily even possible, if you are using a compiler other than MSVC). All that matters is that the setting is added to the .vcxproj file, as per step 3 above.
@mooingduck Yes, and after my comments on your answer here, I have now discovered that passing /SUBSYSTEM:CONSOLE to the linker is actually irrelevant - step 3 is all that matters. Bear in mind my answer relates to makefile projects - in a makefile project, the IDE has no way to know what you're passing to the linker (you might not even be using a compiler which has a /SUBSYSTEM:CONSOLE option), and it is the project itself which keeps track of whether or not it is meant to be a console program. I shall edit my answer accordingly.
@mooingduck I can also confirm that I use this solution myself in a makefile project, with SCons as the build system, and MSVC and MinGW as compilers. There is no other way I know of to get the IDE to pause the console after termination in non-debugging mode.
@chuckleplant I'm afraid not, my workflow was the other way around, calling SCons from VS. I initially manually created my VS makefile projects so that they passed configuration variables to my SCons script (e.g. 32/64 bit, compiler name, release/debug), which then handled the rest of the logic. In that setup there was no need for the project files to ever change, so I didn't use any auto-generating feature of SCons. I've since switched to Linux so I don't use VS anymore. Since it's a VS bug, it might be worth submitting a feature request to SCons to handle the required extra step.
Alternatively, you could just include some Python code in your SCons script to do it yourself each time a project file is generated. I believe VS project files conform to the XML standard, so it should be fairly easy to add the missing elements, and should only require a few lines of code. I would suggest starting here (for Python 2.x) or here (3.x). This answer may also be of interest.
This is a probably an embarasing question as no doubt the answer is blindingly obvious.
I've used Visual Studio for years, but this is the first time I've done any 'Console Application' development.
When I run my application the console window pops up, the program output appears and then the window closes as the application exits.
Is there a way to either keep it open until I have checked the output, or view the results after the window has closed?
23 Answers 23
If you run without debugging (Ctrl+F5) then by default it prompts your to press return to close the window. If you want to use the debugger, you should put a breakpoint on the last line.
If you have a C++ app and Run Without Debugging and the console window still closes, you need to remember to explicitly set the Subsystem to Console under Configuration Properties / Linker / System. This can happen if you start with an Empty Project, which leaves Subsystem unset.
Didn't work for me :( The console window opens and shuts immediately, but the log pauses and waits for an additional press of F5
Trevor Robinson is right. If you start a blank project, and C++ item. You need to go to View->Property Manager->Property(wrench icon)->Config. Properties->Linker->System->Subsystem->in the pop-down menu, choose Console.
Im working on VS community 2017. ctrl+f5 not working, there is no Properties when I right click project, also the wrench icon is greyed out.
Right click on your project
Properties > Configuration Properties > Linker > System
Select Console (/SUBSYSTEM:CONSOLE) in SubSystem option or you can just type Console in the text field!
Now try it. it should work
This worked for my VS2013 Express, but the accepted answer did not. Very strange, as the accepted answer has worked for all Visual Studio versions I've used in the past.
as @JonathanMee stated you still have run Ctrl + F5. This was already set in my visual studio 2015, so the first answer was the one that helped most.
This is indeed correct. The familiar CTRL+F5 will fail if you, say, add a new C++ file to an empty project.
Starting from Visual Studio 2017 (15.9.4) there is an option:
The corresponding fragment from the Visual Studio documentation:
Automatically close the console when debugging stops:
Tells Visual Studio to close the console at the end of a debugging session.
I just tested this in VS2017 and VS2019. It requires both setting the subsystem to CONSOLE and turning this option off. Having one or the other or neither closes the window automatically.
I discovered that if the debugging a C++ console application where command arguments redirect a file to standard input (stdin), the window will automatically close regardless of the setting of this option.
Here is a way for C/C++:
Goto Debug Menu->Press StartWithoutDebugging
It will wait for .
try to call getchar() right before main() returns.
Doesn't work in VS 2008 for a simple Hello Name console app. cout, cin, cout, getchar(), console still closes. What's the deal?
Try putting getchar() twice if you have a cout just before getchar(). getchar() expects a char and you are already giving it with cout. Let me know if this helps :)
(/SUBSYSTEM:CONSOLE) did not worked for my vs2013 (I already had it).
"run without debugging" is not an options, since I do not want to switch between debugging and seeing output.
Solution used in qtcreator pre 2.6. Now while qt is growing, vs is going other way. As I remember, in vs2008 we did not need such tricks.
Here's a solution that (1) doesn't require any code changes or breakpoints, and (2) pauses after program termination so that you can see everything that was printed. It will pause after either F5 or Ctrl+F5. The major downside is that on VS2013 Express (as tested), it doesn't load symbols, so debugging is very restricted.
Create a batch file. I called mine runthenpause.bat , with the following contents:
The first line will run whatever command you provide and up to eight arguments. The second line will. pause.
Open the project properties | Configuration properties | Debugging.
Now, when you run, runthenpause.bat will launch your application, and after your application has terminated, will pause for you to see the console output.
I will post an update if I figure out how to get the symbols loaded. I tried /Z7 per this but without success.
Я начинаю с Visual C++ и хочу знать, как сохранить окно консоли.
Например, это будет типичное приложение "hello world":
Какая черта мне не хватает?
Амрут А. Пиллаи, ваш код не показывает "нажмите любую клавишу, чтобы продолжить", спасибо
Вы можете распечатать это самостоятельно с помощью простого вызова std :: cout.
Обратной стороной всех предлагаемых решений является то, что ни одно из них не работает с отладкой (здесь не работает Ctrl + F5) и когда приложение неожиданно останавливается (здесь не работают все точки останова или чтение из стандартного ввода при основном возврате). Я бы хотел увидеть окно консоли в IDE, такое как у Eclipse и других IDE. Они просто продолжают показывать вывод в stdout / stderr после завершения программы.
@sybren Принятый ответ работает с CTRL + F5, и зачем вам решение, которое работает с отладкой (F5)? Конечно, весь смысл отладки в том, чтобы .. отлаживать? В чем преимущество приостановки консоли после завершения программы в сеансе отладки?
@JBentley Eclipse и другие IDE позволяют вам читать вывод вашей программы даже после завершения процесса. Наверняка вы видите дополнительную выгоду, особенно когда пытаетесь найти ошибку? Кроме того, точка останова работает только тогда, когда вы знаете, где программа завершается, что может быть трудно определить, когда вывод исчезнет с вашего экрана.
@Sybren Не могли бы вы пояснить на примере, когда было бы полезно во время сеанса отладки просмотреть окончательный результат завершенной программы? На мой взгляд, если вас интересует только конечный результат, CTRL-F5 лучше, поскольку запускается быстрее. И если вам нужно больше, то в любом случае необходимо выполнить шаг или установить точку останова, и в этом случае вопрос о незнании точки завершения является спорным. По определению, если ваша программа выполняется прямо до завершения без взаимодействия / проверки разработчика, то вы не отлаживаете.
@JBentley Лично я считаю, что существует разница между общей «отладкой» и конкретным «использованием отладчика VS для пошагового выполнения программы». Также иногда я не знаю, хочу ли я прочитать какой-то записанный вывод, до завершения программы. Другая причина может заключаться в том, что причина прерывания заключается в том же бите кода (например, в сторонней библиотеке), который производит вывод, который я хочу прочитать. Этот вызов библиотеки либо выполняется (выводит вывод, затем завершается), либо нет (вывод не выводится).
@jiggunjer: конечно, знаю, но это не относится к делу. Я не вижу преимущества активного удаления Visual Studio вывода программы после завершения; Я вижу только недостатки.
Будучи разработчиком веб-приложений, легко впасть в заблуждение, считая, что приложение без JavaScript не имеет права на жизнь. Нам становится удобно.
Если вы ищете пакет для быстрой интеграции календаря с выбором даты в ваше приложения, то библиотека Flatpickr отлично справится с этой задачей.
Клиент для URL-адресов, cURL, позволяет взаимодействовать с множеством различных серверов по множеству различных протоколов с синтаксисом URL.
У каждого из нас бывали случаи, когда нам нужно отцентрировать блочный элемент, но мы не знаем, как это сделать. Даже если мы реализуем какой-то.
Ответы 22
Стандартный способ - это cin.get() перед заявлением о возврате.
Это работает, но Ctrl + F5 намного лучше, особенно при отслеживании глобального разрушения объекта и т. д.
Это плохое решение - что, если ваша программа завершится через exit ()?
Alexander Questioning Bresee
-1 для _tmain . Я бы проголосовал еще на -1 за cin.get() вместо того, чтобы устанавливать точку останова для F5 или использовать Ctrl F5. Но мне разрешен только один голос против.
Cheers and hth. - Alf
@Cheers: Что не так с _tmain ? Это стандартный способ написать приложение Windows, ориентированное на подсистему консоли. Отклонение от этого стандарта было бы плохой практикой. Ясно, что здесь никто не говорит о переносимом коде; в вопросе говорится, что Visual C++ и _tmain - это подпись, которая появляется в образце кода. Пора отказаться от этой религии. Windows по умолчанию является «нестандартной», и есть очень веские причины следовать стандартам это.
@CodyGray: Я отрицательно отношусь к _tmain , потому что это совершенно ненужный нестандартный (международный стандарт C++ требует простого main ) и потому, что он использует схему макросов Microsoft T , что является ненужным усложнением и многословием для поддержки Windows 9x. Если вы считаете, что отклонение от стандарта является плохой практикой, вам категорически не следует использовать tmain . Нет никаких веских причин для использования tmain , кроме троллинга или, для профессионалов, для демонстрации своей полной некомпетентности.
Cheers and hth. - Alf
Это взлом. Если вы используете визуальную студию, используйте правильный метод, предложенный Зойдбергом. Если вы не используете визуальную студию, имейте IDE, Makefile, что угодно, выполните пакетный файл, который запускает двоичный результат, а затем приостановите, чтобы окно не закрылось.
«Стандартный способ»? Неужто это только «в одну сторону»?
Это не взлом; это использование языка для выполнения того, что он должен уметь. Опора на IDE - небрежный вариант.
@Grault Это взлом, потому что он использует код для решения проблемы, не связанной с кодом. OP хочет «держать окно консоли открытым» после запуска своего кода внутри IDE. Это решение заставит программу приостанавливаться, независимо от того, запущена она в среде IDE или нет, и есть ли у вас уже незакрывающееся окно консоли или нет - совершенно другой результат. Как вы думаете, хочет ли конечный пользователь программы произвольную паузу при каждом ее запуске только потому, что разработчику нужно, чтобы его окно консоли оставалось открытым, пока он ее пишет? Нет - и проблема, и решение принадлежат IDE, а не программе.
@Grault Ключом к пониманию проблемы с этим решением является понимание того, что держать окно консоли открытым (который требуется в вопросе) и приостановка программы (который решает ответ) являются нет одним и тем же. Сохранение окна консоли открытым является побочным эффектом приостановки программы, поэтому этот ответ работает, но является взломом. К сожалению, в большинстве случаев завершающая пауза не является желательной функцией для консольной программы, которая почти всегда либо запускается из командной строки, либо запускается в фоновом режиме каким-либо другим процессом.
Такая трата энергии на такую придирку. «Ключ к пониманию проблемы . » - это осознать, что проблемы нет, и с этим вряд ли стоит спорить.
Читайте также: