Programming Question Hello World!

BruceJohnJennerLawso

Dread Lord of the Idiots
Addon Developer
Joined
Apr 14, 2012
Messages
2,585
Reaction score
0
Points
36
Hey everyone,

Its been several months since I coded my first program, but Ive restarted my study of C++ programming in the last few weeks. Im posting here to see if anyone can help me with an issue Im having in writing console programs in Windows 7.

Code:
// my first program in C++

#include <iostream>
#include <string>
using namespace std;

int main ()
{

	string Hello = "Hello World!";

	cout <<Hello; return 0;
}

Absolutely stunning isnt it :lol:

Anyways, I have no problems compiling and running the program, but for some reason when I run it on my computer with windows 7, the program runs for a split second, then shuts down. I can tell that its working, as I can just make out some details on the screen in the flash that it is running, but Im now moving on to using cout and cin for input/output, so Ill need to find a way to make it stay on screen. Can anyone offer advice on this?

:hailprobe:
 

Enjo

Mostly harmless
Addon Developer
Tutorial Publisher
Donator
Joined
Nov 25, 2007
Messages
1,665
Reaction score
13
Points
38
Location
Germany
Website
www.enderspace.de
Preferred Pronouns
Can't you smell my T levels?
PHP:
string in;
cin >> in;
return 0;

Never do
PHP:
int in;
cin >> in;
because the program would crash if you entered a character.
 
Last edited:

BruceJohnJennerLawso

Dread Lord of the Idiots
Addon Developer
Joined
Apr 14, 2012
Messages
2,585
Reaction score
0
Points
36
PHP:
string in;
cin >> in;
return 0;

Never do
PHP:
int in;
cin >> in;
because the program will crash if you enter a character.

Thanks, but thats not related to why the program keeps shutting down right away? I havent even tried using cin yet, because I'll need the program to work properly before anyone ever tries to give it an input.
 

Enjo

Mostly harmless
Addon Developer
Tutorial Publisher
Donator
Joined
Nov 25, 2007
Messages
1,665
Reaction score
13
Points
38
Location
Germany
Website
www.enderspace.de
Preferred Pronouns
Can't you smell my T levels?
It is. Try it.
 

Cosmic Penguin

Geek Penguin in GTO
News Reporter
Donator
Joined
Jan 27, 2011
Messages
3,672
Reaction score
2
Points
63
Location
Hong Kong
Hey everyone,

Its been several months since I coded my first program, but Ive restarted my study of C++ programming in the last few weeks. Im posting here to see if anyone can help me with an issue Im having in writing console programs in Windows 7.

Code:
// my first program in C++

#include <iostream>
#include <string>
using namespace std;

int main ()
{

	string Hello = "Hello World!";

	cout <<Hello; return 0;
}

Absolutely stunning isnt it :lol:

Anyways, I have no problems compiling and running the program, but for some reason when I run it on my computer with windows 7, the program runs for a split second, then shuts down. I can tell that its working, as I can just make out some details on the screen in the flash that it is running, but Im now moving on to using cout and cin for input/output, so Ill need to find a way to make it stay on screen. Can anyone offer advice on this?

:hailprobe:

Code:
// my first program in C++

#include <iostream>
#include <string>
using namespace std;

int main ()
{

	string Hello = "Hello World!";

	cout <<Hello; 
[B]system("pause");[/B]
return 0;
}

:hailprobe:

Note that this is actually half of a hack code, as it only works with some of the OS like Windows, but not Linux, and it requires the OS to help pausing running the code. But it works in this example. :tiphat:
 

Enjo

Mostly harmless
Addon Developer
Tutorial Publisher
Donator
Joined
Nov 25, 2007
Messages
1,665
Reaction score
13
Points
38
Location
Germany
Website
www.enderspace.de
Preferred Pronouns
Can't you smell my T levels?
The code that I've posted.
 

BruceJohnJennerLawso

Dread Lord of the Idiots
Addon Developer
Joined
Apr 14, 2012
Messages
2,585
Reaction score
0
Points
36
The code that I've posted.

Ok, I see what you mean, inserting that cin part holds the program open while waiting for an input. When I punch in a value & hit enter the program closes for some reason.

Now the source looks like this

Code:
#include <iostream>
#include <string>
using namespace std;



int main()
{
	string in;
	string Hello = "Hello World!";

	cout <<Hello;
	cin >> in;
	cout <<in;
	return 0;
}

It works beautifully until I give it a in value. Then it shuts down for some reason.
 
Last edited:

Enjo

Mostly harmless
Addon Developer
Tutorial Publisher
Donator
Joined
Nov 25, 2007
Messages
1,665
Reaction score
13
Points
38
Location
Germany
Website
www.enderspace.de
Preferred Pronouns
Can't you smell my T levels?
Because it's instructed to do so: perform its tasks (like file operations, calculations) and exit.
It's the windowed programs which are abnormal in this regard and wait for user input all the time.
 

orb

New member
News Reporter
Joined
Oct 30, 2009
Messages
14,020
Reaction score
4
Points
0
...the program runs for a split second, then shuts down... Can anyone offer advice on this?
That's normal. The program has ended and closed its console window.

You can either set a breakpoint at the end of program, or use one of these inside "#ifdef _DEBUG":
Code:
cin.get ();
std::getchar ();
_getch ();
The `system ("pause")` presented earlier isn't the best example, but it will work in Windows.

Otherwise, the console program shouldn't pause execution waiting for input if it isn't interactive. You can run it in a persistent console window if you want to see the results it printed.
 

BruceJohnJennerLawso

Dread Lord of the Idiots
Addon Developer
Joined
Apr 14, 2012
Messages
2,585
Reaction score
0
Points
36
Because it's instructed to do so: perform its tasks (like file operations, calculations) and exit.
It's the windowed programs which are abnormal in this regard and wait for user input all the time.

So once it hits the end of its source, it automatically closes?

In that case, it probably is getting the input and "couting" it, but its happening in that last frame before shutdown. Ill have to introduce another cin to in order to delay the shutdown.

You can either set a breakpoint at the end of program, or use one of these inside "#ifdef _DEBUG":
Code:
cin.get ();
std::getchar ();
_getch ();
The `system ("pause")` presented earlier isn't the best example, but it will work in Windows.

Otherwise, the console program shouldn't stop execution if it isn't interactive.

Hmmm, the tutorial hasn't even said anything about debugging yet, so I dont know much about break points. Im not sure how to use that last code in my source, where do I put it?

I take it that system pause will basically force me to shut the program down manually?
 

orb

New member
News Reporter
Joined
Oct 30, 2009
Messages
14,020
Reaction score
4
Points
0
I take it that system pause will basically force me to shut the program down manually?

`system ("pause")` will execute the PAUSE command of the system shell, or a program called pause otherwise (or not, if "pause" command nor the executable don't exist).

You want to put one of these just before returning from main.
 

jedidia

shoemaker without legs
Addon Developer
Joined
Mar 19, 2008
Messages
10,877
Reaction score
2,131
Points
203
Location
between the planets
It works beautifully until I give it a in value. Then it shuts down for some reason.

That would be because of:

Code:
return 0;

It closes the function, and therewith the program. If you want it to stay open until a certain input is given, you'll have to loop it, something like:

Code:
int main()
{
	string in;                 
	string Hello = "Hello World! press q to exit";

	cout <<Hello;
        while (in != "q")
        {
             in = "";
	     cin >> in;
        }
	return 0;
}

something like that, anyways. I never used the console since my first tutorials, I'm not exactly sure how cin behaves in that environment, but without resetting in to "" in every part of the loop I would expect it to add the input to in (i.e. if the first input isn't q, the thing will never terminate).

Anyways, the gist is: As soon as return 0; is executed in your main function, the program will terminate, and will pass the value 0 back to show that it has terminated properly.
 
Last edited:

Enjo

Mostly harmless
Addon Developer
Tutorial Publisher
Donator
Joined
Nov 25, 2007
Messages
1,665
Reaction score
13
Points
38
Location
Germany
Website
www.enderspace.de
Preferred Pronouns
Can't you smell my T levels?
So once it hits the end of its source, it automatically closes?
Programs are naturally made to perform tasks. Once a given task is done, defined by the code you've written, it closes, as it doesn't have any other sub task left to do, therefore the entire program's task is considered complete.

---------- Post added at 09:19 PM ---------- Previous post was at 09:16 PM ----------

Anyways, the gist is: As soon as return 0; is executed in your main function, the program will terminate, and will pass the value 0 back to show that it has terminated properly.

It will exit even if there's no "return" command, as there's nothing left to do anyway. Not returning a value is a mistake, though.
 
Last edited:

Quick_Nick

Passed the Turing Test
Donator
Joined
Oct 20, 2007
Messages
4,088
Reaction score
204
Points
103
Location
Tucson, AZ
A good starting program after Hello World would be something that could take input and do simple operations. You can make a loop that repeatedly asks for input (give options like "add" and "quit") and runs until the user inputs "quit" at which point you either break the loop or directly "return 0". An example might help..don't have anything on hand though.
 

BruceJohnJennerLawso

Dread Lord of the Idiots
Addon Developer
Joined
Apr 14, 2012
Messages
2,585
Reaction score
0
Points
36
A good starting program after Hello World would be something that could take input and do simple operations. You can make a loop that repeatedly asks for input (give options like "add" and "quit") and runs until the user inputs "quit" at which point you either break the loop or directly "return 0". An example might help..don't have anything on hand though.

Actually, I was just trying to make something useful, but Im having problems using log from math.h. Witness the birth of the Delta Vee! program (yes it really needs all of the excitement it can get)

Code:
// Delta Vee!
// A calculator for finding the total change in velocity of a spacecraft
#include <iostream>
#include <math.h>
#include <string>
using namespace std;


int main()
{
	double DeeVee;

	string Intro = "Delta Vee!";
	string text1 = "Exhaust Velocity (m/s)";
	string text2 = "Dry Mass (kilograms)";
	string text3 = "Propellant Mass";
	int Vexh;
	int Mp;
	int Md;



	string theory;

	cout <<Intro;
	cin >> Vexh;
	cout <<text1;
	cout <<Vexh;
	cin >> Md;
	cout <<text2;
	cout <<Md;
	cout <<text3;
	cin >> Mp;
	cout <<Mp<< endl;

	DeeVee = Vexh*(log((Mp+Md)/Md));

	cout <<DeeVee;

	cin >> theory;
	return 0;
}

But when I compile, I get this

Code:
1>------ Build started: Project: Delta Vee!, Configuration: Debug Win32 ------
1>  Delta Vee!.cpp
1>Delta Vee!.cpp(36): error C2668: 'log' : ambiguous call to overloaded function
1>          C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\math.h(575): could be 'long double log(long double)'
1>          C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\math.h(527): or       'float log(float)'
1>          C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\math.h(120): or       'double log(double)'
1>          while trying to match the argument list '(int)'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Peculiar, since I did this whole process in the Shuttle-D 1.1 module for a Dv calculator. Why would math.h start bothering me now?

:chainsaw:
 

orb

New member
News Reporter
Joined
Oct 30, 2009
Messages
14,020
Reaction score
4
Points
0
Peculiar, since I did this whole process in the Shuttle-D 1.1 module for a Dv calculator. Why would math.h start bothering me now?

Because you used int type instead of one of listed in the error message (float, double, or long double) for the argument of the function (only overloaded functions for float, double and long double are defined; there isn't one for int). You can either cast the variables to double when you do operations on them or declare them as double (or float).
 

BruceJohnJennerLawso

Dread Lord of the Idiots
Addon Developer
Joined
Apr 14, 2012
Messages
2,585
Reaction score
0
Points
36
Because you used int type instead of one of listed in the error message (float, double, or long double) for the argument of the function (only overloaded functions for float, double and long double are defined; there isn't one for int). You can either cast the variables to double when you do operations on them or declare them as double (or float).

:facepalm:, thanky you Orb!

(Drumroll please)

Code:
// Delta Vee!
// A calculator for finding the total change in velocity of a spacecraft
#include <iostream>
#include <math.h>
#include <string>
#define NEWLINE '\n'
#define TAB '\t'

using namespace std;


int main()
{
	double DeeVee;

	string Intro = "Delta Vee!";
	string Endofprogram = "Shut down?";
	string meterspersecond = "m/s";
	string hailprobe = "Hail the Probe!!!";
	string text1 = "Exhaust Velocity (m/s)";
	string text2 = "Dry Mass (kilograms)";
	string text3 = "Propellant Mass";
	double Vexh;
	double Mp;
	double Md;



	string theory;

	cout <<Intro;
	cout <<NEWLINE;
	cout <<text1;
	cin >> Vexh;
	cout <<text2;
	cin >> Md;
	cout <<text3;
	cin >> Mp;

	DeeVee = Vexh*(log((Mp+Md)/Md));

	cout <<DeeVee;
	cout <<TAB;
	cout <<meterspersecond;
	cout <<NEWLINE;
	cout <<hailprobe;
	cout <<NEWLINE;
	cout <<Endofprogram;
	cin >> theory;
	return 0;
}

(Users note: The program currently allows you to say yes, yes, or really yes to the shut down query. I guess Ill have to fix that next time around :lol:)

:hotcool::woohoo::hotcool:

:hailprobe:
 

Rtyh-12

New member
Joined
Sep 12, 2010
Messages
918
Reaction score
0
Points
0
Location
Kraken Mare
As another beginner programmer, I would like to give you a few pointers (heh...) in case they are helpful.

First, the way you're pausing the execution of the program creates a new, useless string; here's a better way (in my opinion, at least):

Code:
cin.sync(); cin.get();

Just put it wherever you want to pause. When this line is reached, the program will stop and continue when you press the return key.

Also, since I haven't seen this in any of your examples, you don't have to create a string each time you want to print text. Let's take as an example your "Hello world!" program:

Code:
string Hello = "Hello world!";
cout<<Hello;

The following is much cleaner:

Code:
cout<<"Hello world!";

and produces the same output. One more thing, instead of using multiple "cout"s you can just do this:

Code:
int a = 5, b = 10;
cout<<"a is "<<a<<" and b is "<<b<<".";

This produces the output:

Code:
a is 5 and b is 10.
 

BruceJohnJennerLawso

Dread Lord of the Idiots
Addon Developer
Joined
Apr 14, 2012
Messages
2,585
Reaction score
0
Points
36
As another beginner programmer, I would like to give you a few pointers (heh...) in case they are helpful.

First, the way you're pausing the execution of the program creates a new, useless string; here's a better way (in my opinion, at least):

Code:
cin.sync(); cin.get();

Just put it wherever you want to pause. When this line is reached, the program will stop and continue when you press the return key.

Excellent, although I dont understand what any of that code does. I just made a second version that closes only when the user inputs "yes". Its based off of Jedidias example earlier in this thread.

Also, since I haven't seen this in any of your examples, you don't have to create a string each time you want to print text. Let's take as an example your "Hello world!" program:

Code:
string Hello = "Hello world!";
cout<<Hello;

The following is much cleaner:

Code:
cout<<"Hello world!";

and produces the same output. One more thing, instead of using multiple "cout"s you can just do this:

Code:
int a = 5, b = 10;
cout<<"a is "<<a<<" and b is "<<b<<".";

This produces the output:

Code:
a is 5 and b is 10.

All good stuff, but if I make it so that users can opt to keep going (instead of "shut down?", "shut down or go again?"), it might be a little faster to have them defined generically? It seems fifty-fifty to me, but thanks for showing me that method.

:hailprobe:
 
Top