0
#include<iostream.h>


class car
{
     float price;
     public:
     void a_price()
     {
         cout<<"Price :";
         cin>>price;
     }
 };

void main()
{
     car ford;
     ford.a_price;

 }

it will get the entry of price from user and then disappears the console and if i write getch() then it will stay why we have to write that ? this is the concept of c language. and if i write

      int main ()
      {
          block of code

      return 0;
       }

then also console is disappears. and if am writing below code then console stays perfect:

#include<iostream.h>
#include<conio.h>

class car
{
     float price;
     public:
     void a_price()
     {
         cout<<"Price :";
         cin>>price;
     }
 };

void main()
{
     car ford;
     ford.a_price;
     getch();
 }

and to clear screen why we have to use system("cls"); when we have clrscr();

Drashti
  • 111
  • 2
  • 12
  • 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) – Braca Jul 10 '18 at 11:21
  • no it is diffrent from that because i want to know the use why we are using of getch() in c++ and why we cannot use clrscr() in c++ ? if we can use getch() then clrscr() has to work too... – Drashti Jul 10 '18 at 11:27
  • using `getch()' waits for input, that's what is preventing console to close. What do you mean by 'cannot use clrscr()'? – Braca Jul 10 '18 at 11:47
  • thank you i understand what u want to say and clrscr() also works in c++ but why we have to type getch() in every code ? why console disappears every time ? – Drashti Jul 10 '18 at 11:58

1 Answers1

0

When you run your program from GUI it creates the console window, runs, and when it finishes the console window is closed automatically. There are many ways of preventing this depending on your OS, IDE ...

getch() at the end is expecting input, so it prevents console from closing (not in all cases, for more details see this answer).

Instead of trying to prevent closing you can run your program from terminal (command line - CLI). If you are new to programming you should learn some terminal basics. If you are using Windows:

<Windows key + r> will open the 'run' dialog box. Type 'cmd' and press enter. With your console open change current directory to your program directory:

cd /d "path to directory your program is in"

you can view the content of the directory with dir command, and run your program by typing it's name. Use <TAB> for autocomplete in console window.

Braca
  • 2,685
  • 17
  • 28