I started to learn C++ few days ago. When I Run a program it show a console window for a moment then return to IDE. I even couldn't see the output.
for example followig Hello World Program

// a small C++ program
#include <iostream>
using namespace std;
int main()
{
    cout << "Hello, world!" << endl;
    
}

what should I add in this code (infact every code) to stop this problem. I tried to fix it myself by adding cin.ignore(); at the end of the program. But this doesn't workout where program requires the input from user.

Re: Newbie Question (Hello World) 80 80

i am not in front of windows, so i can't test the advise::

try inserting system("pause"); and in the beginning <include> <cstdlib>

-i am not sure about which library to include...i am sure about the system command

another way would be to declare a dummy variable and read it at the end of the programm....

Re: Newbie Question (Hello World) 80 80

I would not recommend using

system("pause");

as it is not portable between various operating systems...try something like

cin.get();

at the end instead...

Re: Newbie Question (Hello World) 80 80

I tried to fix it myself by adding cin.ignore(); at the end of the program. But this doesn't workout where program requires the input from user.

It doesn't work because there's still something in the stream and ignore gets it right away. You should clear the stream first then do ignore or get.

#include <iostream>

using namespace std;

void BlockPause() {
  // Set the state so cin can read.
  cin.clear();

  // Clear everything in the stream
  cin.sync();

  // Do the pause
  cin.ignore();
}

int main() {
  // All of your other code goes here

  // Pause at the end with BlockPause
  cout<<"Press enter to continue...";
  BlockPause();

  return 0;
}

cin.clear() makes the stream state good. If it's not good, cin won't read anything ever. cin.sync() clears all of the characters left in the stream so that the next cin.ignore() or cin.get() stops the program waiting for input.

Re: Newbie Question (Hello World) 80 80

You should use
getch();
at the end!

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

int main()
{
cout << "Hello world!";
getch();
return 0;
}

or press alt+F5 at the end of program.

Re: Newbie Question (Hello World) 80 80

You should use
getch();
at the end!

No you really shouldn't. It's non-portable.

Better would be to learn how to execute a command-line program from the command line.

And please use [code] [/code] tags.

Re: Newbie Question (Hello World) 80 80

add
#include<iostream.h>
#include<conio.h>
int main()
{
cout<<"hello world";
getch(); //is used to hold the o/p screen
return 0; //will return the value to O.S.
}

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.