0

I have below program written in c++.

#include<iostream.h>
void main() {
    int age = 0;
    cout<<"Please enter age\n";
    cin>>age;
    cout<<"Your age is - ";
    cout<<age;
}

After entering the age, it closes the screen. I can't see the output. I could it by pressing the Alt + F5 only.

Is it possible to check the output right after entering the age by pressing the enter key?

Pankaj
  • 9,749
  • 32
  • 139
  • 283
  • I guess it is more a windows problem than c++; try launching your program from a console manually or ask for the terminal not to close when finished – OznOg Jun 23 '20 at 11:27
  • Run the program from terminal or command prompt – Shan S Jun 23 '20 at 11:27
  • 1
    That's the normal behavior of console applications being run from a GUI.Interactive console programs aren't really intended to run directly from a GUI environment, instead they are intended to be run from an already open console or terminal program (like the "Command Prompt"). – Some programmer dude Jun 23 '20 at 11:28
  • Just as an FYI, `iostream.h` has been gone for a long time and you might be running a very outdated compiler (you won't be learning standard C++). – crashmstr Jun 23 '20 at 11:28
  • However, you *could* ask the user to press the `Enter` key to exit, and then read a line (discarding all input) until you get a newline. But that will affect the running behavior of your program when run from a console as well, as then the user still have to press the `Enter` key to exit. – Some programmer dude Jun 23 '20 at 11:30
  • 1
    That's the normal behavior of console applications being run from a GUI... **on Windows**. – DevSolar Jun 23 '20 at 12:00

2 Answers2

2

You can ask the user to press enter or type a certain character to exit.

#include<iostream.h>
void main() {
    int age = 0;
    cout<<"Please enter age\n";
    cin>>age;
    cout<<"Your age is - ";
    cout<<age;
    cin.get();
}

Note1: Avoid system("PAUSE") --> system("pause"); - Why is it wrong?

Note2 In some IDE's like codeblocks the behaviour change.

CodeBlocks will wait for you to press any key before closing to output screen even if main returns 0

EEAH
  • 715
  • 4
  • 17
0

Adding this file: #include<conio.h> worked for me.

#include<iostream.h>
#include<conio.h>
void main() {
    int age = 0;
    cout<<"Please enter age\n";
    cin>>age;
    cout<<"Your age is - ";
    cout<<age;
    getch();
}
Pankaj
  • 9,749
  • 32
  • 139
  • 283