Закрывается консоль при ошибке visual studio

Console application (build) closes if an error occures, how can I let the console stay open after the error occures? (For debbuging reasons, and yes the application has to be build for my purposes)

Console.ReadKey() is not what I am looking for, just wondering if I can prevent the exit on error.

asked Mar 10, 2022 at 12:21

Erik's user avatar

3

answered Mar 10, 2022 at 12:36

huneriann's user avatar

1

The piece of code which can casue exception should be written inside

try{} catch{}

Example: In this for loop first iteration should give an Index out bound error but still it continues to print ignoring the exception case. In catch you can do whatever you want to do with the exception.

int v = 100;
int[] a = new int[v];
for (int i = 0; i < v; i++)`
{
    try
    {
        Console.WriteLine(a[i - 1].ToString() + " - Count: " + i);
    }
    catch
    {}
}

answered Mar 10, 2022 at 12:37

Ansari Aquib's user avatar

2

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?

sorin's user avatar

sorin

157k171 gold badges521 silver badges783 bronze badges

asked Nov 21, 2009 at 15:58

Martin's user avatar

1

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.

answered Nov 21, 2009 at 16:00

Tom's user avatar

TomTom

20.7k4 gold badges42 silver badges54 bronze badges

12

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

Bhargav Rao's user avatar

Bhargav Rao

48.5k28 gold badges123 silver badges138 bronze badges

answered Mar 24, 2013 at 5:38

Viraj's user avatar

VirajViraj

2,5271 gold badge11 silver badges2 bronze badges

5

Starting from Visual Studio 2017 (15.9.4) there is an option:

Tools->Options->Debugging->Automatically close the console

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.

Community's user avatar

answered Jan 8, 2019 at 1:19

chronoxor's user avatar

chronoxorchronoxor

2,9093 gold badges19 silver badges31 bronze badges

5

Here is a way for C/C++:

#include <stdlib.h>

#ifdef _WIN32
    #define WINPAUSE system("pause")
#endif

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.

carefulnow1's user avatar

answered Aug 6, 2012 at 15:16

Shaun's user avatar

ShaunShaun

5154 silver badges2 bronze badges

5

Goto Debug Menu->Press StartWithoutDebugging

answered Sep 28, 2012 at 9:24

pashaplus's user avatar

pashapluspashaplus

3,4382 gold badges25 silver badges24 bronze badges

2

If you’re using .NET, put Console.ReadLine() before the end of the program.

It will wait for <ENTER>.

answered Nov 21, 2009 at 16:00

Cheeso's user avatar

CheesoCheeso

188k99 gold badges468 silver badges712 bronze badges

4

try to call getchar() right before main() returns.

Alex Shesterov's user avatar

answered Apr 4, 2013 at 17:34

Magarusu's user avatar

MagarusuMagarusu

88210 silver badges14 bronze badges

2

(/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.

I ended with

int main() {
  ...
#if _DEBUG
  LOG_INFO("end, press key to close");
  getchar();
#endif // _DEBUG
  return 0;
}

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.

answered Oct 15, 2014 at 14:35

Fantastory's user avatar

FantastoryFantastory

1,84321 silver badges25 bronze badges

0

just put as your last line of code:

system("pause");

answered Jan 9, 2018 at 22:59

RafaelJan's user avatar

RafaelJanRafaelJan

2,8381 gold badge26 silver badges40 bronze badges

0

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.

  1. Create a batch file. I called mine runthenpause.bat, with the following contents:

    %1 %2 %3 %4 %5 %6 %7 %8 %9
    pause
    

    The first line will run whatever command you provide and up to eight arguments. The second line will… pause.

  2. Open the project properties | Configuration properties | Debugging.

  3. Change «Command Arguments» to $(TargetPath) (or whatever is in «Command»).
  4. Change «Command» to the full path to runthenpause.bat.
  5. Hit OK.

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.

Community's user avatar

answered Jul 20, 2016 at 23:14

cxw's user avatar

cxwcxw

16.4k2 gold badges44 silver badges78 bronze badges

1

add “| pause” in command arguments box under debugging section at project properties.

answered Nov 28, 2009 at 20:13

theambient's user avatar

1

You could run your executable from a command prompt. This way you could see all the output. Or, you could do something like this:

int a = 0;
scanf("%d",&a);

return YOUR_MAIN_CODE;

and this way the window would not close until you enter data for the a variable.

answered Nov 21, 2009 at 17:30

Geo's user avatar

GeoGeo

91.8k115 gold badges343 silver badges516 bronze badges

Just press CNTRL + F5 to open it in an external command line window (Visual Studio does not have control over it).

If this doesn’t work then add the following to the end of your code:

Console.WriteLine("Press any key to exit...");
Console.ReadKey();

This wait for you to press a key to close the terminal window once the code has reached the end.

If you want to do this in multiple places, put the above code in a method (e.g. private void Pause()) and call Pause() whenever a program reaches a possible end.

answered Jan 30, 2015 at 19:48

carefulnow1's user avatar

carefulnow1carefulnow1

78311 silver badges29 bronze badges

2

A somewhat better solution:

atexit([] { system("PAUSE"); });

at the beginning of your program.

Pros:

  • can use std::exit()
  • can have multiple returns from main
  • you can run your program under the debugger
  • IDE independent (+ OS independent if you use the cin.sync(); cin.ignore(); trick instead of system("pause");)

Cons:

  • have to modify code
  • won’t pause on std::terminate()
  • will still happen in your program outside of the IDE/debugger session; you can prevent this under Windows using:

extern "C" int __stdcall IsDebuggerPresent(void);
int main(int argc, char** argv) {
    if (IsDebuggerPresent())
        atexit([] {system("PAUSE"); });
    ...
}

answered Oct 23, 2017 at 20:37

GhassanPL's user avatar

GhassanPLGhassanPL

2,6515 gold badges32 silver badges39 bronze badges

3

Either use:

  1. cin.get();

or

  1. system("pause");

Make sure to make either of them at the end of main() function and before the return statement.

answered Apr 14, 2018 at 23:08

AAEM's user avatar

AAEMAAEM

1,8272 gold badges17 silver badges26 bronze badges

You can also use this option

#include <conio.h> 
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main() {
   .
   .
   .
   getch(); 

   return 0;
}

answered Oct 17, 2018 at 5:37

Vladimir Salguero's user avatar

In my case, i experienced this when i created an Empty C++ project on VS 2017 community edition. You will need to set the Subsystem to «Console (/SUBSYSTEM:CONSOLE)» under Configuration Properties.

  1. Go to «View» then select «Property Manager»
  2. Right click on the project/solution and select «Property». This opens a Test property page
  3. Navigate to the linker then select «System»
  4. Click on «SubSystem» and a drop down appears
  5. Choose «Console (/SUBSYSTEM:CONSOLE)»
  6. Apply and save
  7. The next time you run your code with «CTRL +F5», you should see the output.

answered Dec 3, 2018 at 13:31

0xsteve's user avatar

0xsteve0xsteve

1011 silver badge4 bronze badges

Sometimes a simple hack that doesnt alter your setup or code can be:

Set a breakpoint with F9, then execute Debug with F5.

answered May 17, 2021 at 8:06

user1323995's user avatar

user1323995user1323995

1,1761 gold badge9 silver badges16 bronze badges

Since running it from VS attaches the VS debugger, you can check for an attached debugger:

if (Debugger.IsAttached)
{
    Console.WriteLine("Debugger is attached. Press any key to exit.");
    Console.ReadKey();
}

I guess the only caveat is that it’ll still pause if you attach any other debugger, but that may even be a wanted behavior.

answered Oct 17, 2021 at 11:56

Juan's user avatar

JuanJuan

15.1k23 gold badges99 silver badges184 bronze badges

Visual Studio 2015, with imports. Because I hate
when code examples don’t give the needed imports.

#include <iostream>;

int main()
{
    getchar();
    return 0;
}

answered Jul 14, 2017 at 2:57

KANJICODER's user avatar

KANJICODERKANJICODER

3,47729 silver badges16 bronze badges

Currently there is no way to do this with apps running in WSL2. However there are two work-arounds:

  1. The debug window retains the contents of the WSL shell window that closed.

  2. The window remains open if your application returns a non-zero return code, so you could return non-zero in debug builds for example.

answered Sep 1, 2020 at 9:41

It should be added that things have changed since then. On Windows 11 (probably 10, I can’t check any more) the new Terminal app that now houses the various console, PowerShell and other sessions has its own settings regarding closing. Look for it in Settings > Defaults > Advanced > Profile termination behavior.

If it’s set to close when a program exits with zero, then it will close, even if VS is told otherwise.

answered Jun 28, 2022 at 13:59

Gábor's user avatar

GáborGábor

9,0873 gold badges59 silver badges77 bronze badges

Go to Setting>Debug>Un-check close on end.

enter image description here

answered Jun 27, 2020 at 16:32

Priyanshu Singh's user avatar

1

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?

sorin's user avatar

sorin

157k171 gold badges521 silver badges783 bronze badges

asked Nov 21, 2009 at 15:58

Martin's user avatar

1

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.

answered Nov 21, 2009 at 16:00

Tom's user avatar

TomTom

20.7k4 gold badges42 silver badges54 bronze badges

12

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

Bhargav Rao's user avatar

Bhargav Rao

48.5k28 gold badges123 silver badges138 bronze badges

answered Mar 24, 2013 at 5:38

Viraj's user avatar

VirajViraj

2,5271 gold badge11 silver badges2 bronze badges

5

Starting from Visual Studio 2017 (15.9.4) there is an option:

Tools->Options->Debugging->Automatically close the console

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.

Community's user avatar

answered Jan 8, 2019 at 1:19

chronoxor's user avatar

chronoxorchronoxor

2,9093 gold badges19 silver badges31 bronze badges

5

Here is a way for C/C++:

#include <stdlib.h>

#ifdef _WIN32
    #define WINPAUSE system("pause")
#endif

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.

carefulnow1's user avatar

answered Aug 6, 2012 at 15:16

Shaun's user avatar

ShaunShaun

5154 silver badges2 bronze badges

5

Goto Debug Menu->Press StartWithoutDebugging

answered Sep 28, 2012 at 9:24

pashaplus's user avatar

pashapluspashaplus

3,4382 gold badges25 silver badges24 bronze badges

2

If you’re using .NET, put Console.ReadLine() before the end of the program.

It will wait for <ENTER>.

answered Nov 21, 2009 at 16:00

Cheeso's user avatar

CheesoCheeso

188k99 gold badges468 silver badges712 bronze badges

4

try to call getchar() right before main() returns.

Alex Shesterov's user avatar

answered Apr 4, 2013 at 17:34

Magarusu's user avatar

MagarusuMagarusu

88210 silver badges14 bronze badges

2

(/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.

I ended with

int main() {
  ...
#if _DEBUG
  LOG_INFO("end, press key to close");
  getchar();
#endif // _DEBUG
  return 0;
}

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.

answered Oct 15, 2014 at 14:35

Fantastory's user avatar

FantastoryFantastory

1,84321 silver badges25 bronze badges

0

just put as your last line of code:

system("pause");

answered Jan 9, 2018 at 22:59

RafaelJan's user avatar

RafaelJanRafaelJan

2,8381 gold badge26 silver badges40 bronze badges

0

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.

  1. Create a batch file. I called mine runthenpause.bat, with the following contents:

    %1 %2 %3 %4 %5 %6 %7 %8 %9
    pause
    

    The first line will run whatever command you provide and up to eight arguments. The second line will… pause.

  2. Open the project properties | Configuration properties | Debugging.

  3. Change «Command Arguments» to $(TargetPath) (or whatever is in «Command»).
  4. Change «Command» to the full path to runthenpause.bat.
  5. Hit OK.

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.

Community's user avatar

answered Jul 20, 2016 at 23:14

cxw's user avatar

cxwcxw

16.4k2 gold badges44 silver badges78 bronze badges

1

add “| pause” in command arguments box under debugging section at project properties.

answered Nov 28, 2009 at 20:13

theambient's user avatar

1

You could run your executable from a command prompt. This way you could see all the output. Or, you could do something like this:

int a = 0;
scanf("%d",&a);

return YOUR_MAIN_CODE;

and this way the window would not close until you enter data for the a variable.

answered Nov 21, 2009 at 17:30

Geo's user avatar

GeoGeo

91.8k115 gold badges343 silver badges516 bronze badges

Just press CNTRL + F5 to open it in an external command line window (Visual Studio does not have control over it).

If this doesn’t work then add the following to the end of your code:

Console.WriteLine("Press any key to exit...");
Console.ReadKey();

This wait for you to press a key to close the terminal window once the code has reached the end.

If you want to do this in multiple places, put the above code in a method (e.g. private void Pause()) and call Pause() whenever a program reaches a possible end.

answered Jan 30, 2015 at 19:48

carefulnow1's user avatar

carefulnow1carefulnow1

78311 silver badges29 bronze badges

2

A somewhat better solution:

atexit([] { system("PAUSE"); });

at the beginning of your program.

Pros:

  • can use std::exit()
  • can have multiple returns from main
  • you can run your program under the debugger
  • IDE independent (+ OS independent if you use the cin.sync(); cin.ignore(); trick instead of system("pause");)

Cons:

  • have to modify code
  • won’t pause on std::terminate()
  • will still happen in your program outside of the IDE/debugger session; you can prevent this under Windows using:

extern "C" int __stdcall IsDebuggerPresent(void);
int main(int argc, char** argv) {
    if (IsDebuggerPresent())
        atexit([] {system("PAUSE"); });
    ...
}

answered Oct 23, 2017 at 20:37

GhassanPL's user avatar

GhassanPLGhassanPL

2,6515 gold badges32 silver badges39 bronze badges

3

Either use:

  1. cin.get();

or

  1. system("pause");

Make sure to make either of them at the end of main() function and before the return statement.

answered Apr 14, 2018 at 23:08

AAEM's user avatar

AAEMAAEM

1,8272 gold badges17 silver badges26 bronze badges

You can also use this option

#include <conio.h> 
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main() {
   .
   .
   .
   getch(); 

   return 0;
}

answered Oct 17, 2018 at 5:37

Vladimir Salguero's user avatar

In my case, i experienced this when i created an Empty C++ project on VS 2017 community edition. You will need to set the Subsystem to «Console (/SUBSYSTEM:CONSOLE)» under Configuration Properties.

  1. Go to «View» then select «Property Manager»
  2. Right click on the project/solution and select «Property». This opens a Test property page
  3. Navigate to the linker then select «System»
  4. Click on «SubSystem» and a drop down appears
  5. Choose «Console (/SUBSYSTEM:CONSOLE)»
  6. Apply and save
  7. The next time you run your code with «CTRL +F5», you should see the output.

answered Dec 3, 2018 at 13:31

0xsteve's user avatar

0xsteve0xsteve

1011 silver badge4 bronze badges

Sometimes a simple hack that doesnt alter your setup or code can be:

Set a breakpoint with F9, then execute Debug with F5.

answered May 17, 2021 at 8:06

user1323995's user avatar

user1323995user1323995

1,1761 gold badge9 silver badges16 bronze badges

Since running it from VS attaches the VS debugger, you can check for an attached debugger:

if (Debugger.IsAttached)
{
    Console.WriteLine("Debugger is attached. Press any key to exit.");
    Console.ReadKey();
}

I guess the only caveat is that it’ll still pause if you attach any other debugger, but that may even be a wanted behavior.

answered Oct 17, 2021 at 11:56

Juan's user avatar

JuanJuan

15.1k23 gold badges99 silver badges184 bronze badges

Visual Studio 2015, with imports. Because I hate
when code examples don’t give the needed imports.

#include <iostream>;

int main()
{
    getchar();
    return 0;
}

answered Jul 14, 2017 at 2:57

KANJICODER's user avatar

KANJICODERKANJICODER

3,47729 silver badges16 bronze badges

Currently there is no way to do this with apps running in WSL2. However there are two work-arounds:

  1. The debug window retains the contents of the WSL shell window that closed.

  2. The window remains open if your application returns a non-zero return code, so you could return non-zero in debug builds for example.

answered Sep 1, 2020 at 9:41

It should be added that things have changed since then. On Windows 11 (probably 10, I can’t check any more) the new Terminal app that now houses the various console, PowerShell and other sessions has its own settings regarding closing. Look for it in Settings > Defaults > Advanced > Profile termination behavior.

If it’s set to close when a program exits with zero, then it will close, even if VS is told otherwise.

answered Jun 28, 2022 at 13:59

Gábor's user avatar

GáborGábor

9,0873 gold badges59 silver badges77 bronze badges

Go to Setting>Debug>Un-check close on end.

enter image description here

answered Jun 27, 2020 at 16:32

Priyanshu Singh's user avatar

1

I’m using Visual Studio 2010 and Windows 7 x64

The command prompt closes after exit, even though I used «Start without debug». Is there a setting somewhere that I can use?

asked Nov 7, 2010 at 14:12

segfault's user avatar

1

You can simply press Ctrl+F5 instead of F5 to run the built code. Then it will prompt you to press any key to continue. Or you can use this line -> system("pause"); at the end of the code to make it wait until you press any key.

However, if you use the above line, system("pause"); and press Ctrl+F5 to run, it will prompt you twice!

rink.attendant.6's user avatar

answered Jan 22, 2013 at 12:23

Suhas Bharadwaj's user avatar

Suhas BharadwajSuhas Bharadwaj

1,3051 gold badge14 silver badges9 bronze badges

8

Yes, in VS2010 they changed this behavior somewhy.
Open your project and navigate to the following menu: Project -> YourProjectName Properties -> Configuration Properties -> Linker -> System. There in the field SubSystem use the drop-down to select Console (/SUBSYSTEM:CONSOLE) and apply the change.
«Start without debugging» should do the right thing now.

Or, if you write in C++ or in C, put

system("pause");

at the end of your program, then you’ll get «Press any key to continue…» even when running in debug mode.

cmsjr's user avatar

cmsjr

55.4k11 gold badges70 silver badges62 bronze badges

answered May 14, 2011 at 13:48

lapis's user avatar

lapislapis

6,7444 gold badges33 silver badges38 bronze badges

3

What about Console.Readline();?

rink.attendant.6's user avatar

answered Nov 7, 2010 at 14:16

Rahul Soni's user avatar

Rahul SoniRahul Soni

4,8733 gold badges32 silver badges58 bronze badges

Add a Console.ReadKey call to your program to force it to wait for you to press a key before exiting.

answered Nov 7, 2010 at 14:17

SLaks's user avatar

SLaksSLaks

856k175 gold badges1885 silver badges1953 bronze badges

1

You could open a command prompt, CD to the Debug or Release folder, and type the name of your exe. When I suggest this to people they think it is a lot of work, but here are the bare minimum clicks and keystrokes for this:

  • in Visual Studio, right click your project in Solution Explorer or the tab with the file name if you have a file in the solution open, and choose Open Containing Folder or Open in Windows Explorer
  • in the resulting Windows Explorer window, double-click your way to the folder with the exe
  • Shift-right-click in the background of the explorer window and choose Open Commmand Window here
  • type the first letter of your executable and press tab until the full name appears
  • press enter

I think that’s 14 keystrokes and clicks (counting shift-right-click as two for example) which really isn’t much. Once you have the command prompt, of course, running it again is just up-arrow, enter.

answered Nov 7, 2010 at 17:40

Kate Gregory's user avatar

Kate GregoryKate Gregory

18.8k8 gold badges56 silver badges85 bronze badges

1

Очень часто новички сталкиваются с такой проблемой: запускают программу, а консоль закрывается после выполнения программы и не дает просмотреть результат ее работы. В этот статье мы поговорим о том, что нужно сделать, чтобы этого избежать.

Рассмотрим программу на языке C, которая выводит в консоль надпись «Hello world!»:

#include <stdio.h>

int main ()

{

    printf(«Hello world!n»);

    return 0;

}

Запустим программу, для этого нажмем в Visual Studio клавишу F5. Консоль появляется и мгновенно исчезает. Существуют два пути решения этой проблемы.

Первый. Самый простой. Нажать одновременно клавиши Ctrl и F5. Смотрим результат:

consoleIsNotclosedC1

Второй способ (которым почему-то пользуется большинство начинающих. Дописать в конце программы функцию, которая считывает символ с клавиатуры (_getch(), чтобы эта функция работала, подключаем библиотеку <conio.h>), тем самым программа ждет ввода символа и консоль не закрывается, а мы смотрим на результат ее работы.

#include <stdio.h>

#include <conio.h>

int main ()

{

    printf(«Hello world!n»);

    _getch();

    return 0;

}

consoleIsNotclosedC2

Теперь рассмотрим пример этой же программы на языке C#

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace consoleIsNotclosedCSharp

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine(«Hello world!»);

        }

    }

}

Если выполнить запуск программы в Visual Studio, нажав F5, мы ничего не увидим: консоль быстро закроется. Поэтому необходимо нажимать одновременно Ctrl и F5, либо дописать функцию Console.ReadLine(), которая будет ожидать ввода строки:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace consoleIsNotclosedCSharp

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine(«Hello world!»);

            Console.ReadLine();

        }

    }

}

Запустив программу, мы увидим, что консоль не закрывается после выполнения программы, и теперь есть возможность прочитать выводимую фразу: «Hello world!». Нажав клавишу Enter, завершим программу.

Скачать исходники программ можно, нажав кнопку ниже.

Скачать исходники

ObjectOne > C++ > MVS 2012 > Visual Studio — Если консоль открывается и сразу закрывается

Странная штука, решил протестировать ещё одно приложенице но тут консолька стала чудить на секунду открываться и опять исчезать. Правильное решение было найдено в одном из вопросов по теме. Не дискредитируйте идеи консольного программирования не вставляйте функции а меняйте настройки среды разработки. Решение чуть ниже.

  1. Проект — Свойства
  2. Поменяйте настрйку подсистемы

TheCalligrapher

Программа «выключается» потому, что вы ее так и написали — выполняющейся без остановки и сразу завершающейся — и выполняете ее не из консоли.

Вставлять в консольное придложение всякие ‘cin.get()’ или ‘system(«pause»)’ — это грязное программироване и дискредитация идеи консольного приложения. Если вы пользуетесь Microsoft Visual Studio, то поставьте в установках проекта SUBSYSTEM=CONSOLE и запускайте свою программу без дебаггера (Ctrl+F5). Окно консоли не будет закрываться по завершению программы. Если же вы ползуетесь другой средой — смотрите документацию на тему того, как это делается там.

( http://www.cyberforum.ru/cpp-beginners/thread1672058.html )

Количество просмотров: 12 324

| Категория: MVS 2012
| Тэги: консоль

  • Remove From My Forums
  • Вопрос

  • Создал простейшее C++/CLR консольное приложение в MS VS 2010. Запускаю его клавишами Ctrl+F5, как для других приложений, однако консольное окно не ожидает нажатия какой-нибудь клавиши, а моментально закрывается.

    Это очередной баг MS VS 2010? В чем проблема-то?! Никакие установки проекта я не менял.

Ответы

  • Попробуйте изменить стандартное поведение как написано
    тут.

    • Помечено в качестве ответа

      15 февраля 2013 г. 11:58

  • Здравствуйте Сыроежка,

    Насколько я понимаю, ответ на Ваш изначальный вопрос был дан, так что будьте добры его отметить, чтобы другие пользователи с таким же вопросом увидели его. Что касается бага, если считаете это таковым, то можете написать баг репорт. Вот ссылочка:
    https://connect.microsoft.com/VisualStudio

    Спасибо

    • Помечено в качестве ответа
      Abolmasov Dmitry
      15 февраля 2013 г. 11:59
  • Как не имеет:

    • Предложено в качестве ответа
      I.Zaytsev
      4 июня 2013 г. 6:23
    • Помечено в качестве ответа
      YatajgaModerator
      4 июня 2013 г. 11:03

19 ответов

Если вы запускаете без отладки (Ctrl + F5), то по умолчанию он предлагает вам нажать return, чтобы закрыть окно. Если вы хотите использовать отладчик, вы должны поставить точку останова в последней строке.

Tom
21 нояб. 2009, в 17:13

Поделиться

Щелкните правой кнопкой мыши на вашем проекте

Свойства> Свойства конфигурации> Линкер> Система

Выберите Console (/SUBSYSTEM: CONSOLE) в опции SubSystem или вы можете просто ввести Console в текстовое поле!

Теперь попробуйте… это должно работать

Viraj
24 март 2013, в 06:34

Поделиться

Вот способ для C/С++:

#include <stdlib.h>

#ifdef _WIN32
    #define WINPAUSE system("pause")
#endif

Поместите это вверху вашей программы, и ЕСЛИ он находится в системе Windows (#ifdef _WIN32), тогда он создаст макрос с именем WINPAUSE. Всякий раз, когда вы хотите, чтобы ваша программа приостанавливалась, вызовите WINPAUSE;, и она приостанавливает программу, используя команду DOS. Для других систем, таких как Unix/Linux, консоль не должна выходить из выхода программы в любом случае.

Shaun
06 авг. 2012, в 16:28

Поделиться

Откройте меню отладки- > Нажмите Начать без использования

pashaplus
28 сен. 2012, в 10:20

Поделиться

Если вы используете .NET, поместите Console.ReadLine() до конца программы.

Он будет ждать <ENTER>.

Cheeso
21 нояб. 2009, в 17:08

Поделиться

попробуйте вызвать getchar() прямо перед возвратом main().

Magarusu
04 апр. 2013, в 18:06

Поделиться

(/SUBSYSTEM: CONSOLE) не работал для моего vs2013 (у меня его уже было).

«run without debugging» не является параметром, так как я не хочу переключаться между отладкой и просмотром вывода.

Я закончил с

int main() {
  ...
#if _DEBUG
  LOG_INFO("end, press key to close");
  getchar();
#endif // _DEBUG
  return 0;
}

Решение, используемое в qtcreator до 2.6. Теперь, когда qt растет, vs идет другим путем. Насколько я помню, в vs2008 нам не нужны такие трюки.

fantastory
15 окт. 2014, в 16:18

Поделиться

Здесь решение, что (1) не требует каких-либо изменений кода или точек останова, и (2) приостанавливается после завершения программы, чтобы вы могли видеть все, что было напечатано. Он остановится после F5 или Ctrl + F5. Основной недостаток заключается в том, что на VS2013 Express (как проверено) он не загружает символы, поэтому отладка очень ограничена.

  • Создайте командный файл. Я назвал мой runthenpause.bat со следующим содержимым:

    %1 %2 %3 %4 %5 %6 %7 %8 %9
    pause
    

    Первая строка будет запускать любую команду, которую вы предоставляете, и до восьми аргументов. Вторая строка будет… пауза.

  • Откройте свойства проекта | Конфигурационные свойства | Отладка.

  • Измените «Аргументы команд» на $(TargetPath) (или что-то еще в «Команде» ).
  • Измените «Команда» на полный путь до runthenpause.bat.
  • Нажмите ОК.

Теперь, когда вы запустите, runthenpause.bat запустит ваше приложение, и после того, как ваше приложение завершится, вы остановитесь, чтобы увидеть вывод консоли.

Я опубликую обновление, если выясню, как загрузить символы. Я пробовал /Z7 за этот, но безуспешно.

cxw
21 июль 2016, в 00:45

Поделиться

просто введите свою последнюю строку кода:

system("pause");

RefaelJan
10 янв. 2018, в 00:45

Поделиться

Просто нажмите CNTRL + F5, чтобы открыть его во внешнем окне командной строки (Visual Studio не контролирует его).

Если это не сработает, добавьте следующее в конец вашего кода:

Console.WriteLine("Press any key to exit...");
Console.ReadKey();

Подождите, пока вы нажмете клавишу, чтобы закрыть окно терминала, как только код достигнет конца.

Если вы хотите сделать это в нескольких местах, поместите вышеуказанный код в метод (например, private void Pause()) и вызовите Pause() всякий раз, когда программа достигает возможного конца.

carefulnow1
30 янв. 2015, в 20:32

Поделиться

добавить «| pause» в поле аргументов команды в разделе отладки в свойствах проекта.

theambient
28 нояб. 2009, в 21:40

Поделиться

Вы можете запустить исполняемый файл из командной строки. Таким образом, вы можете увидеть весь вывод. Или вы можете сделать что-то вроде этого:

int a = 0;
scanf("%d",&a);

return YOUR_MAIN_CODE;

и таким образом окно не будет закрываться, пока вы не введете данные для переменной a.

Geo
21 нояб. 2009, в 18:26

Поделиться

Либо используйте:

  1. cin.get();

или

  1. system("pause");

Обязательно сделайте любой из них в конце функции main() и перед оператором return.

AAEM
15 апр. 2018, в 00:10

Поделиться

Несколько лучшее решение:

atexit([] { system("PAUSE"); });

в начале вашей программы.

Плюсы:

  • может использовать std:: exit()
  • может иметь несколько возвратов из основного
  • вы можете запустить свою программу под отладчиком
  • Независимый IDE (+ независимый от ОС, если вы используете трюк cin.sync(); cin.ignore(); вместо system("pause");)

Минусы:

  • необходимо изменить код
  • не будет останавливаться на std:: terminate()
  • все равно произойдет в вашей программе вне сеанса IDE/debugger; вы можете предотвратить это под Windows, используя:

extern "C" int __stdcall IsDebuggerPresent(void);
int main(int argc, char** argv) {
    if (IsDebuggerPresent())
        atexit([] {system("PAUSE"); });
    ...
}

GhassanPL
23 окт. 2017, в 21:06

Поделиться

Начиная с Visual Studio 2017 (15.9.4) есть опция:

Tools->Options->Debugging->Automatically close the console

Соответствующий фрагмент из документации Visual Studio:

Автоматически закрывать консоль при остановке отладки:

Сообщает Visual Studio закрыть консоль в конце сеанса отладки.

chronoxor
08 янв. 2019, в 02:24

Поделиться

В моем случае я испытал это, когда создал проект Empty C++ в версии VS 2017 для сообщества. Вам нужно будет установить для подсистемы значение «Консоль (/SUBSYSTEM: CONSOLE)» в разделе «Свойства конфигурации».

  1. Зайдите в «Просмотр», затем выберите «Менеджер недвижимости»
  2. Щелкните правой кнопкой мыши на проекте/решении и выберите «Свойство». Откроется страница свойств теста.
  3. Перейдите к компоновщику, затем выберите «Система»
  4. Нажмите «Подсистема» и появится выпадающий
  5. Выберите «Консоль (/SUBSYSTEM: CONSOLE)»
  6. Применить и сохранить
  7. В следующий раз, когда вы запустите свой код с помощью «CTRL +F5», вы должны увидеть результат.

Stephen Haruna
03 дек. 2018, в 14:42

Поделиться

Вы также можете использовать эту опцию

#include <conio.h> 
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main() {
   .
   .
   .
   getch(); 

   return 0;
}

Vladimir Salguero
17 окт. 2018, в 06:49

Поделиться

Visual Studio 2015, импорт. Потому что я ненавижу
когда примеры кода не дают необходимых импортов.

#include <iostream>;

int main()
{
    getchar();
    return 0;
}

J.M.I. MADISON
14 июль 2017, в 04:36

Поделиться

Используйте console.readline. Ваш пишет строку, но не читает ее.

Dallas
20 апр. 2011, в 02:51

Поделиться

Ещё вопросы

  • 1Что я делаю не так с async / await?
  • 0Angular JS с проблемами маршрутизации Ruby on Rails
  • 0Div результаты, вложенные друг в друга
  • 0Увеличить регулярное выражение
  • 0Значение по умолчанию для MySQL с использованием другого столбца
  • 0Получить пользователей, которые должны оплатить в один день sql
  • 0Скрыть номера с помощью JavaScript, без использования JQuery
  • 0Цикл по массиву с помощью кнопки
  • 0Оператор равенства для части результата
  • 1Nexus One Dev Phone против обычного телефона Nexus One (розничная версия)
  • 1Android-медиа плеер
  • 0Как переключать динамически создаваемые div’ы на основе атрибутов класса и имени?
  • 1Замените переменные в файле .docx на введенные пользователем переменные
  • 1Получить размер базы данных Rethinkdb с помощью Python
  • 1Android Wi-Fi: «Семейство адресов не поддерживается»
  • 0запрос обработки на стороне сервера play Framework равен нулю
  • 0Привязка значения в функцию ожидания в JavaScript
  • 1объем файла jp-пакета webpack — файл функций импорта
  • 0Как я могу проверить метод void, который вставляет запись в базу данных, используя Junit?
  • 1Упрощенное дублирование атрибутов регулярных выражений
  • 1API RemoteService путаницы
  • 0Jquery Script работает только в режиме редактирования, Sharepoint
  • 1Изменение ориентации PDF с помощью Itext
  • 1после сопоставления. все экземпляры повторяющейся группы соответствия, python
  • 1Redux Form — заполнение начальных значений
  • 0Можно ли синхронизировать действия в cocos2d-x?
  • 1как избежать усадки участков в шпионах?
  • 1Как я могу отложить предупреждение и перезагрузить, чтобы аудио файл мог воспроизводиться в javascript?
  • 0Валидация с использованием AngularJS
  • 0Как получить значение из сцены, которую я передал из другой сцены в cocos2d для Android?
  • 0Highcharts — Добавить разницу между y-точками
  • 0Обновить нулевое поле из того же поля, если не ноль
  • 0Как добавить стиль в класс span
  • 1org.hibernate.LazyInitializationException: не удалось инициализировать прокси — нет сеанса. Spring + Hibernate + HSQLDB
  • 1Запись аудио в Android
  • 0Как установить мою локальную файловую систему в качестве хранилища композитора для моей среды разработки?
  • 0Как сдвинуть биты с прямым порядком байтов в C ++
  • 1Как автоматизировать parse.unquote (), .clipboard_append () и т. Д. В Python — tkinter
  • 1Как перебрать DataFrame, если применить не будет без цикла for?
  • 1Вызов функции внутри If..If Else..Else внутри скрипта google-app
  • 1TFS SDK 2013 Получить имена команд в заданном командном проекте
  • 0Адаптируйте ширину 3-го блока подряд с помощью CSS
  • 0angular — как я могу разобрать параметры запроса из отдельной строки
  • 1Операция со списком файлов не удалась после нескольких раундов
  • 0Как передать переменную в контроллер из директивы, которая находится за пределами контроллера?
  • 0Найти элемент для кнопки или изображения
  • 1Как построить доверительные интервалы для функции stattools ccf?
  • 1Полимер 2.0 класса наследственно защищенных свойств
  • 0Можно ли конвертировать из .php в .xml после завершения обработки?
  • 0Не могу заставить мой алгоритм сжатия работать правильно

Очень часто новички сталкиваются с такой проблемой: запускают программу, а консоль закрывается после выполнения программы и не дает просмотреть результат ее работы. В этот статье мы поговорим о том, что нужно сделать, чтобы этого избежать.

Рассмотрим программу на языке C, которая выводит в консоль надпись «Hello world!»:

#include <stdio.h>

int main ()

{

    printf(«Hello world!n»);

    return 0;

}

Запустим программу, для этого нажмем в Visual Studio клавишу F5. Консоль появляется и мгновенно исчезает. Существуют два пути решения этой проблемы.

Первый. Самый простой. Нажать одновременно клавиши Ctrl и F5. Смотрим результат:

consoleIsNotclosedC1

Второй способ (которым почему-то пользуется большинство начинающих. Дописать в конце программы функцию, которая считывает символ с клавиатуры (_getch(), чтобы эта функция работала, подключаем библиотеку <conio.h>), тем самым программа ждет ввода символа и консоль не закрывается, а мы смотрим на результат ее работы.

#include <stdio.h>

#include <conio.h>

int main ()

{

    printf(«Hello world!n»);

    _getch();

    return 0;

}

consoleIsNotclosedC2

Теперь рассмотрим пример этой же программы на языке C#

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace consoleIsNotclosedCSharp

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine(«Hello world!»);

        }

    }

}

Если выполнить запуск программы в Visual Studio, нажав F5, мы ничего не увидим: консоль быстро закроется. Поэтому необходимо нажимать одновременно Ctrl и F5, либо дописать функцию Console.ReadLine(), которая будет ожидать ввода строки:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace consoleIsNotclosedCSharp

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine(«Hello world!»);

            Console.ReadLine();

        }

    }

}

Запустив программу, мы увидим, что консоль не закрывается после выполнения программы, и теперь есть возможность прочитать выводимую фразу: «Hello world!». Нажав клавишу Enter, завершим программу.

Скачать исходники программ можно, нажав кнопку ниже.

Скачать исходники

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?

sorin's user avatar

sorin

160k175 gold badges532 silver badges799 bronze badges

asked Nov 21, 2009 at 15:58

Martin's user avatar

1

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.

answered Nov 21, 2009 at 16:00

Tom's user avatar

TomTom

20.8k4 gold badges42 silver badges54 bronze badges

12

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

Bhargav Rao's user avatar

Bhargav Rao

49.6k28 gold badges121 silver badges140 bronze badges

answered Mar 24, 2013 at 5:38

Viraj's user avatar

VirajViraj

2,5671 gold badge12 silver badges2 bronze badges

6

Starting from Visual Studio 2017 (15.9.4) there is an option:

Tools->Options->Debugging->Automatically close the console

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.

Community's user avatar

answered Jan 8, 2019 at 1:19

chronoxor's user avatar

chronoxorchronoxor

3,0793 gold badges19 silver badges31 bronze badges

6

Here is a way for C/C++:

#include <stdlib.h>

#ifdef _WIN32
    #define WINPAUSE system("pause")
#endif

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.

carefulnow1's user avatar

answered Aug 6, 2012 at 15:16

Shaun's user avatar

ShaunShaun

5154 silver badges2 bronze badges

6

Goto Debug Menu->Press StartWithoutDebugging

answered Sep 28, 2012 at 9:24

pashaplus's user avatar

pashapluspashaplus

3,5662 gold badges26 silver badges25 bronze badges

2

If you’re using .NET, put Console.ReadLine() before the end of the program.

It will wait for <ENTER>.

answered Nov 21, 2009 at 16:00

Cheeso's user avatar

CheesoCheeso

189k101 gold badges469 silver badges713 bronze badges

4

try to call getchar() right before main() returns.

Alex Shesterov's user avatar

answered Apr 4, 2013 at 17:34

Magarusu's user avatar

MagarusuMagarusu

96210 silver badges14 bronze badges

2

(/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.

I ended with

int main() {
  ...
#if _DEBUG
  LOG_INFO("end, press key to close");
  getchar();
#endif // _DEBUG
  return 0;
}

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.

answered Oct 15, 2014 at 14:35

Fantastory's user avatar

FantastoryFantastory

1,87321 silver badges25 bronze badges

0

just put as your last line of code:

system("pause");

answered Jan 9, 2018 at 22:59

RafaelJan's user avatar

RafaelJanRafaelJan

3,0381 gold badge28 silver badges46 bronze badges

0

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.

  1. Create a batch file. I called mine runthenpause.bat, with the following contents:

    %1 %2 %3 %4 %5 %6 %7 %8 %9
    pause
    

    The first line will run whatever command you provide and up to eight arguments. The second line will… pause.

  2. Open the project properties | Configuration properties | Debugging.

  3. Change «Command Arguments» to $(TargetPath) (or whatever is in «Command»).
  4. Change «Command» to the full path to runthenpause.bat.
  5. Hit OK.

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.

Community's user avatar

answered Jul 20, 2016 at 23:14

cxw's user avatar

cxwcxw

16.6k2 gold badges45 silver badges81 bronze badges

1

add “| pause” in command arguments box under debugging section at project properties.

answered Nov 28, 2009 at 20:13

theambient's user avatar

1

You could run your executable from a command prompt. This way you could see all the output. Or, you could do something like this:

int a = 0;
scanf("%d",&a);

return YOUR_MAIN_CODE;

and this way the window would not close until you enter data for the a variable.

answered Nov 21, 2009 at 17:30

Geo's user avatar

GeoGeo

92.9k117 gold badges342 silver badges519 bronze badges

Just press CNTRL + F5 to open it in an external command line window (Visual Studio does not have control over it).

If this doesn’t work then add the following to the end of your code:

Console.WriteLine("Press any key to exit...");
Console.ReadKey();

This wait for you to press a key to close the terminal window once the code has reached the end.

If you want to do this in multiple places, put the above code in a method (e.g. private void Pause()) and call Pause() whenever a program reaches a possible end.

answered Jan 30, 2015 at 19:48

carefulnow1's user avatar

carefulnow1carefulnow1

80312 silver badges30 bronze badges

2

A somewhat better solution:

atexit([] { system("PAUSE"); });

at the beginning of your program.

Pros:

  • can use std::exit()
  • can have multiple returns from main
  • you can run your program under the debugger
  • IDE independent (+ OS independent if you use the cin.sync(); cin.ignore(); trick instead of system("pause");)

Cons:

  • have to modify code
  • won’t pause on std::terminate()
  • will still happen in your program outside of the IDE/debugger session; you can prevent this under Windows using:

extern "C" int __stdcall IsDebuggerPresent(void);
int main(int argc, char** argv) {
    if (IsDebuggerPresent())
        atexit([] {system("PAUSE"); });
    ...
}

answered Oct 23, 2017 at 20:37

GhassanPL's user avatar

GhassanPLGhassanPL

2,6695 gold badges32 silver badges40 bronze badges

3

Either use:

  1. cin.get();

or

  1. system("pause");

Make sure to make either of them at the end of main() function and before the return statement.

answered Apr 14, 2018 at 23:08

AAEM's user avatar

AAEMAAEM

1,8272 gold badges17 silver badges26 bronze badges

You can also use this option

#include <conio.h> 
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main() {
   .
   .
   .
   getch(); 

   return 0;
}

answered Oct 17, 2018 at 5:37

Vladimir Salguero's user avatar

In my case, i experienced this when i created an Empty C++ project on VS 2017 community edition. You will need to set the Subsystem to «Console (/SUBSYSTEM:CONSOLE)» under Configuration Properties.

  1. Go to «View» then select «Property Manager»
  2. Right click on the project/solution and select «Property». This opens a Test property page
  3. Navigate to the linker then select «System»
  4. Click on «SubSystem» and a drop down appears
  5. Choose «Console (/SUBSYSTEM:CONSOLE)»
  6. Apply and save
  7. The next time you run your code with «CTRL +F5», you should see the output.

answered Dec 3, 2018 at 13:31

0xsteve's user avatar

0xsteve0xsteve

1011 silver badge4 bronze badges

Sometimes a simple hack that doesnt alter your setup or code can be:

Set a breakpoint with F9, then execute Debug with F5.

answered May 17, 2021 at 8:06

user1323995's user avatar

user1323995user1323995

1,2761 gold badge10 silver badges16 bronze badges

Since running it from VS attaches the VS debugger, you can check for an attached debugger:

if (Debugger.IsAttached)
{
    Console.WriteLine("Debugger is attached. Press any key to exit.");
    Console.ReadKey();
}

I guess the only caveat is that it’ll still pause if you attach any other debugger, but that may even be a wanted behavior.

answered Oct 17, 2021 at 11:56

Juan's user avatar

JuanJuan

15.2k23 gold badges103 silver badges185 bronze badges

This is a detailed explanation for latest Visual Studio releases that worked for me:

  • Go to Solution Explorer by pressing CTRL + ALT + L, then right click on it and choose Properties. on the left side, double click Linker then choose System, then click on SubSystem and type CONSOLE, then click Apply.

  • Click on Tools then Options..., then go to the search bar (CTRL + E) and search for console then click Enter, then click on Debugging then General then disable Automatically close the console when debugging stops.

After that, press CTRL + F5 to start without debugging. and, Voilà!

answered May 19 at 17:28

iTzVoko's user avatar

iTzVokoiTzVoko

1252 silver badges10 bronze badges

Visual Studio 2015, with imports. Because I hate
when code examples don’t give the needed imports.

#include <iostream>;

int main()
{
    getchar();
    return 0;
}

answered Jul 14, 2017 at 2:57

KANJICODER's user avatar

KANJICODERKANJICODER

3,58130 silver badges17 bronze badges

Currently there is no way to do this with apps running in WSL2. However there are two work-arounds:

  1. The debug window retains the contents of the WSL shell window that closed.

  2. The window remains open if your application returns a non-zero return code, so you could return non-zero in debug builds for example.

answered Sep 1, 2020 at 9:41

It should be added that things have changed since then. On Windows 11 (probably 10, I can’t check any more) the new Terminal app that now houses the various console, PowerShell and other sessions has its own settings regarding closing. Look for it in Settings > Defaults > Advanced > Profile termination behavior.

If it’s set to close when a program exits with zero, then it will close, even if VS is told otherwise.

answered Jun 28, 2022 at 13:59

Gábor's user avatar

GáborGábor

9,2863 gold badges63 silver badges79 bronze badges

Go to Setting>Debug>Un-check close on end.

enter image description here

answered Jun 27, 2020 at 16:32

Priyanshu Singh's user avatar

1

slavik57

0 / 0 / 0

Регистрация: 27.04.2014

Сообщений: 62

1

Закрывается консоль

27.02.2016, 21:02. Показов 19071. Ответов 5

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;
 
int main()
{
    double g, f;
    cout << "vvedit chislo galonov" << endl;
    cin >> g;
    f = g / 4.481;
    cout << "colvo funtov" << endl;
    cout << f << endl;
    return 0;
}

В чём проблема ребят, почему программа открывается просит ввести значение и после ввода и нажатия ентер выключается

Отладка:

Кликните здесь для просмотра всего текста

«ConsoleApplication6.exe» (Win32). Загружено «C:UsersPZDocumentsVisual Studio 2013ProjectsConsoleApplication6DebugConsoleApplication6.exe». Символы загружены.
«ConsoleApplication6.exe» (Win32). Загружено «C:WindowsSysWOW64ntdll.dll». Символы загружены.
«ConsoleApplication6.exe» (Win32). Загружено «C:WindowsSysWOW64kernel32.dll». Символы загружены.
«ConsoleApplication6.exe» (Win32). Загружено «C:WindowsSysWOW64KernelBase.dll». Символы загружены.
«ConsoleApplication6.exe» (Win32). Загружено «C:WindowsSysWOW64msvcp120d.dll». Символы загружены.
«ConsoleApplication6.exe» (Win32). Загружено «C:WindowsSysWOW64msvcr120d.dll». Символы загружены.
Программа «[7264] ConsoleApplication6.exe» завершилась с кодом 0 (0x0).



0



Модератор

Эксперт С++

13320 / 10454 / 6253

Регистрация: 18.12.2011

Сообщений: 27,908

27.02.2016, 21:10

2



0



Lost17

181 / 47 / 33

Регистрация: 27.02.2016

Сообщений: 260

27.02.2016, 21:11

3

Лучший ответ Сообщение было отмечено slavik57 как решение

Решение

После 11-ой строки попробуй добавить:

C++
1
system("pause");



0



Hikari

Хитрая блондиночка $)

1471 / 986 / 399

Регистрация: 21.12.2015

Сообщений: 3,785

27.02.2016, 21:12

4

Перед return напиши

C++
1
cin.get()

или

C++
1
system("pause");

если виндовс.



0



0 / 0 / 0

Регистрация: 27.04.2014

Сообщений: 62

27.02.2016, 21:17

 [ТС]

5

спасибо, помогло



0



Вездепух

Эксперт CЭксперт С++

10975 / 5960 / 1628

Регистрация: 18.10.2014

Сообщений: 14,956

27.02.2016, 21:22

6

Цитата
Сообщение от slavik57
Посмотреть сообщение

В чём проблема ребят, почему программа открывается просит ввести значение и после ввода и нажатия ентер выключается

Программа «выключается» потому, что вы ее так и написали — выполняющейся без остановки и сразу завершающейся — и выполняете ее не из консоли.

Вставлять в консольное придложение всякие ‘cin.get()’ или ‘system(«pause»)’ — это грязное программироване и дискредитация идеи консольного приложения. Если вы пользуетесь Microsoft Visual Studio, то поставьте в установках проекта SUBSYSTEM=CONSOLE и запускайте свою программу без дебаггера (Ctrl+F5). Окно консоли не будет закрываться по завершению программы. Если же вы ползуетесь другой средой — смотрите документацию на тему того, как это делается там.



2



  • Закрыв книгу все сразу забылось где ошибка
  • Заз сенс ошибка р0480
  • Закройте переднюю крышку kyocera ошибка
  • Зажигай на устах улыбки зажигай не боясь ошибки
  • Закройте автоподатчик оригиналов kyocera ошибка что делать