View Full Version : newbie question
airborn9_78
06-23-2004, 03:01 PM
hi i'm a total newbie and only started c++ today , i have tried this code:
#include <stdio.h>
main()
{
printf ("Hello, world.\n");
}
i want o know why , when it is executed it does stay open , and what do i do to keep it open ? cheers
shmoove
06-23-2004, 03:17 PM
It runs, it finishes running, and then it closes. Exactly like it's supposed to.
You could:
a) Run it from the console. Instead of clicking the exe, open a console window (those DOS thingies) and run it from there. The console window won't close when the program is finished.
b) Add a command like getch() or something at the end. That will cause it to wait until you enter a char.
c) If you're using Visual Studio, run it in Debug mode (F5), and the IDE will add a pause for you.
shmoove
whackaxe
06-23-2004, 06:28 PM
if you're learning C++, iostream is more common i think. using cin.get gets anything, so you just hit enter and thats it.
#include <iostream.h>
int main
{
cout<<"hello world"<<endl;
cin.get();
return(1);
}
Serex
06-25-2004, 06:20 AM
#include <stdio.h>
main()
{
printf ("Hello, world.\n");
system("pause"); // also works
}
obiwanjabroni
06-30-2004, 05:41 PM
You're problem programming in Windows or a related operating system. What you're referring to is a problem in which your program executes but never quits. That's because Windows derivitives need to receive an exit code. This tells the operating system if your program was executed successfully or if there was an error.
Therefore, most text/console windows programs will have:
int main()
as the entrypoint, the int specifying the return type for your function. By the way, the generic main will serve you all the way until you start programming specific applications for Windows.
Usually, at the end of your int main(), you will have a return statement. This is what exits your application. Now, this is where you return an integer, specifying how your program ran. For programs written under Windows, a successful run is:
return 0;
You don't want to concern yourself with other uses of return, but for now, the return will terminate the program if its executed from main(). Used elsewhere, like in functions (basically, subroutines that you use to split up the tasks in your program so its factored), it exits the function and returns to the function that called it. You'll eventually get used to this. Hope that helps. Oh, and the complete code for a correctly functioning Hello World program like that, using C++ standards is:
#include <iostream.h>
int main()
{
cout << "Hello, world." << endl;
return 0;
}
This will output exactly the same thing as what you had, but will close the program once finished. It also uses "cout", which is based on the C++ architecture (you'll find that C is the base language while C++ brings in the object-oriented architecture, which is what the iostream library uses).
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.