Программирование на C, C# и Java
Уроки программирования, алгоритмы, статьи, исходники, примеры программ и полезные советы
ОСТОРОЖНО МОШЕННИКИ! В последнее время в социальных сетях участились случаи предложения помощи в написании программ от лиц, прикрывающихся сайтом vscode.ru. Мы никогда не пишем первыми и не размещаем никакие материалы в посторонних группах ВК. Для связи с нами используйте исключительно эти контакты: vscoderu@yandex.ru, https://vk.com/vscode
Если консоль закрывается после выполнения программы
Очень часто новички сталкиваются с такой проблемой: запускают программу, а консоль закрывается после выполнения программы и не дает просмотреть результат ее работы. В этот статье мы поговорим о том, что нужно сделать, чтобы этого избежать.
Рассмотрим программу на языке C, которая выводит в консоль надпись «Hello world!»:
Запустим программу, для этого нажмем в Visual Studio клавишу F5. Консоль появляется и мгновенно исчезает. Существуют два пути решения этой проблемы.
Первый. Самый простой. Нажать одновременно клавиши Ctrl и F5. Смотрим результат:
cgmichael
Если ОС не Windows, то вместо строки system (“pause”) можно использовать cin.get().
Также возможен следующий вариант с getch():
Если вы пользуетесь Visual Studio и запускаете свою программу в пошаговом отладчике (Start Debugging – F5), то эта проблема вас вообще не должна интересовать. Если же вы запускаете программу на полноценное выполнение (Start Without Debugging – Ctrl+F5), то консольное окно и так не должно закрываться при завершении программы.
Если же оно у вас таки закрывается, то идите в настройки проекта Project->Properties->’Linker -> System’ и исправьте настройку ‘SubSystem’ на ‘Console’. Окно перестанет закрываться само по себе, а будет просить вас нажать клавишу, как это делает системная команда “pause”.
Preventing console window from closing on Visual Studio C/C++ Console application
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?
24 Answers 24
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.
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
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.
![]()
Here is a way for C/C++:
Put this at the top of your program, and IF it is on a Windows system ( #ifdef _WIN32 ), then it will create a macro called WINPAUSE . Whenever you want your program to pause, call WINPAUSE; and it will pause the program, using the DOS command. For other systems like Unix/Linux, the console should not quit on program exit anyway.
![]()
Goto Debug Menu->Press StartWithoutDebugging
If you’re using .NET, put Console.ReadLine() before the end of the program.
It will wait for <ENTER> .
try to call getchar() right before main() returns.
![]()
(/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.
just put as your last line of code:
![]()
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.
Как сделать чтобы консоль не закрывалась c после выполнения
Изучая язык C# на примере создания консольных приложений, сталкивался с неприятной штукой, что приложение, завершив работу, автоматически закрывалось. Сначала придумал такой способ — запускать из консоли cmd приложение, которое предварительно компилировал в Visual Studio. Но в таком случае мне приходилось сначала нажимать кнопку Build Solution (Ctrl + Shift + B), а в соседнем окне с консолью запускать созданное приложение (Рис.1).
Рис.1. Запуск консольного приложения из консоли
Чтоб не выполнять лишних действий, нужно заставить приложение не закрываться автоматически. Делается это добавлением ожидания нажатия кнопки. Пока кнопка не нажата, окно не будет закрыто. Для добавление привычности выведем на экране сообщение «Press any key to continue», после чего приложение будет закрыто. Такое типичное поведение
Теперь при нажатии кнопки Start debugging (F5) или Start without debugging (Ctrl + F5) будет автоматически открываться консольное приложение и оно не будет закрыто до тех пор, пока не будет нажата любая кнопка на клавиатуре.