C++ not working properly

george2

Daemon Poster
Messages
553
I'm teaching myself c++ and I did the Hello World program and saved it into a folder and everything got it compiled and then ran it when I did that all it did was flash a Dos text box for a second and then close it. What did I do wrong. Here's the code.


#include <iostream>
using namespace std;

int main ()
{
cout << "Hello World!";
return 0;
}
 
you need to add

getchar();

before return 0;

This waits for keyboard input from the user. (Return, I think).
 
you could also add system(pause);

in reality there is nothing wrong with the program, it runs, gives an output and then finishes, try running it from a dos box and you'll see the output inside that box.
 
nor will adding getchar() since thats not a hello world program.

the correct syntax for using get char would be

int main();
{
char x;
cout << "Hello World!";
x = getchar();
return 0;
}

since it scans the keyboard loading the key pressed into variable, (so marks off for not using the function properly,

besides getchar is not needed, as I said in the previous post, the program acualy works perfectly, (it runs) and it finishes. without error...
getchar() or system(pause) simply arn't needed.

marks off for using the function because he simply doesn't need it!

besides which, who said anything about a degree?
 
Hey thanks for that I know that the program works but I just wanted to know how to stop it from just flashing on the screen for a second.
 
http://computerforums.org/showthread.php?t=6279

Using an input function to pause something is bad practice.

Someone could overflow the buffer and give random results, crash the program, could even crash the system, rewrite to memory it's not suppose to. Big security risk. It's not probable that they could do it to a hello world program cause of the speed of execution is too quick.
 
Back
Top Bottom