Program exits after taking input

2019-09-21 16:28发布

问题:

I have been going through C++ Primer Plus and I am working on the programming challenges in it using Visual Studio Code since there were weird issues with Visual Studio 2017. I have looked at a lot of other similar posts but the solutions there don't work for me. For example I tried putting a breakpoint at the main() function's closing curly brace, putting in cin.ignore() at the end before return 0. But none of that works. Here is the code.

#include <iostream>

using namespace std;

int main() {
    int inInput;
    cout << "Enter your height in inches." << endl;
    cin >> inInput;
    int feet = inInput/12;
    int inches = inInput%12;
    cout << feet << inches << " is your height." << endl;
    cin.ignore();
    return 0;

}

Edit:

Tried the solution that this was marked as a duplicate of and it didn't work.

回答1:

I tried to launch your code and as last line (before return) I putted cin.get(); line. After that my window are not closing.

Also, you may add one more line of cin.ignore(); or change existing one to cin.ignore(2)and it will also help you. The reason why it closing, because after this line executed

cin >> inInput;

still \n is inside input buffer. So first cin.ignore() is only ignoring one \n and shut down console applciation by its natural way.

p.s. A few more ways to wait:

  • C++ Console applications exit immediately when run
  • very basic C++ program closes after user input for no particular reason?

It is just default mode for console application: close after finishing executing program.

Hope it will help! Good luck!