0

Hi I'm a highschool student in need of help. I am interested in C++ as I wish to become a programmer one day. I started using Visual Studio for C++ and I'm running a few simple lines of code. But everytime I press (Ctrl + F5) or Local Windows Debugger it shows my line of code but it closes out immediately after it runs, making it near impossible to read. The code is the classic "Hello World!" code. Maybe it has to do something with return 0;?

EDIT: Here's my code.

#include <iostream>
using namespace std;

int main()
{
    int mark = 90;
    if (mark < 50) {
        cout << "HES OLD" << endl; 
    }
    else {
        cout << "Hes not old!" << endl;
    }
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • Setting a break point to `return 0;`? – MikeCAT Apr 13 '16 at 16:20
  • Are you sure `CTRL+F5` does not pause the console? It does for me. Otherwise dupe of: http://stackoverflow.com/questions/1775865/preventing-console-window-from-closing-on-visual-studio-c-c-console-applicatio – NathanOliver Apr 13 '16 at 16:21

1 Answers1

0

When making console applications, I use the following lines at the end of my main function:

std::cout << "\nPaused. Press Enter to continue.\n";
std::cin.ignore(100000, '\n');

The idea is to display a prompt and then wait for the Enter key to be pressed.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
  • Could this also be accomplished with a while loop that just continues looping until enter is pressed? – Stephen Apr 13 '16 at 16:32
  • I don't need fancy things. This works, but I just want my code to display what it was told to, not pressing anything. –  Apr 13 '16 at 16:37
  • @Stephen: If you use platform specific code to check for key press, then you can use a `while` loop checking for the enter key. Otherwise, the `cin` will terminate it's input gathering when an Enter key is pressed. – Thomas Matthews Apr 13 '16 at 16:43
  • @stivodivo: You will need to come up with code that will prevent the console window from closing, usually until the User wants the console closed. Maybe sleeping forever? Most operating systems will close the console window when the associated executable terminates. – Thomas Matthews Apr 13 '16 at 16:44