Reputation: 1
I am doing a console application for training. When I debug the code below, it closes itself before displaying
std::cout << e << std::endl;
If I moved the integer e and its output before std::cout << "Enter a number:";
it works normally, but when listed like below only its input works, and the console closes itself.
#include "stdafx.h"
#include <iostream>
int raisemath()
{
std::cout << "Enter an integer: "; // ask user for an integer
int a; // allocate a variable to hold the user input
std::cin >> a; // get user input from console and store in variable a
return a; // return this value to the function's caller (main)
}
int main()
{
int number;
std::cout << "Enter a number:";
std::cin >> number;
std::cout << "You entered " << number << std::endl;
int e = raisemath();
std::cout << e << std::endl;
return 0;
}
I want to know why?
Upvotes: 0
Views: 203
Reputation: 549
After the last std::cout
there is nothing stopping the console from closing.
When you change the std::cout
's position there is an input-statement coming after it. So the console waits for the input to continue with the execution.
Preventing the console from closing can be easily achieved by adding a breakpoint at the last return statement or a blank input before the return statement.
You might also want to check your debugger settings to see if the "Automatically close the console when debugging stops" is checked or not. (It's in Tools>Options>Debugging)
Upvotes: 1