-1

I am taking a beginner's C++ class. At home, I was trying to duplicate a BMI calculator using std::cin to get data and std::cout to ask questions when I ran into a problem. The terminal would close whenever I pressed enter after typing the first std::cin. It was working fine in class, could somebody tell me what's going on?

  • 5
    Please [show](https://stackoverflow.com/posts/48370471/edit) the relevant code as a [mcve]. – Ron Jan 21 '18 at 18:52
  • 3
    If you have a debugger, just add a breakpoint right before `return 0;` – L.Y. Sim Jan 21 '18 at 18:54
  • 3
    Possible duplicate of [How to stop C++ console application from exiting immediately?](https://stackoverflow.com/questions/2529617/how-to-stop-c-console-application-from-exiting-immediately) – Brien Foss Jan 21 '18 at 18:57

2 Answers2

0

When you run code, it goes line-by-line and executes it. Because your code got to the last line, it stopped, and closed the terminal. I recommend either using a while loop or another std::cin >> at the end.

George_E -old
  • 188
  • 1
  • 3
  • 17
  • If you call your program from a terminal you wont have that problem, but you can use getchar(); to solve your problem – jeyejow Jan 21 '18 at 19:38
0

If you run the program as a standalone executable it will close the terminal once it is finished. You can halt the execution at the end using a function like system("PAUSE") on Windows/DOS, or something that requests input like std::cin.get() at the end if you need your code to be cross-platform. This will wait for some input so you can see the output of the program and then you can exit it by typing some input.

mdatsev
  • 3,054
  • 13
  • 28
  • 2
    `system("PAUSE");` is a Windows/DOS specific hack, not a general cross-platform solution. Also; using `system` in the first place is horrible; have fun with all the nasty security issues. – Jesper Juhl Jan 21 '18 at 18:57
  • 2
    Yes, I stated that OP can use this if on windows, I will add DOS. Also the question is tagged with `windows`, so I find this appropriate. – mdatsev Jan 21 '18 at 18:58
  • The CRT's `system` function doesn't use CMD's `/d` option to disable executing "AutoRun" commands, so it may end up running arbitrary commands. It's better to implement this yourself with `_write` and `_getch`, and not that complicated. Or just spawn an instance of CMD or PowerShell when exiting. By default, the shell will attach to the current console to keep it open. – Eryk Sun Jan 23 '18 at 02:30