The Daily Click ::. Forums ::. Non-Klik Coding Help ::. Guide to C++
 

Post Reply  Post Oekaki 
 

Posted By Message

ShadowCaster

Possibly Insane

Registered
  02/01/2002
Points
  2203
19th April, 2004 at 07:47:21 -

Hi all
Since the forums have just changed again, I may as well be the first to post something here to get things going. If something I say doenst make sense, be sure to tell me and I'll try to update it to make it more readible.

I'll try and add to this every once in a while; whenever I dont have a million things to do for uni

I've written three short examples while I was waiting for the database to upload, so here they are...

Mike

 
"Now I guess we're... 'Path-E-Tech Management'" -Dilbert

ShadowCaster

Possibly Insane

Registered
  02/01/2002
Points
  2203
19th April, 2004 at 07:57:16 -

ShadowCaster's Guide to C++
Part 1: Hello, World


01: #include <iostream>
Before any data can be sent from the program to the command window, we first need to import the iostream class. A class is simply a grouping of code which you can import and use in your own application. The #include statement simply copies all the code from the iostream file into your file when you compile the application.

02: void main()

03: {
In C++, every application must contain a function called "main", as this is where your program will start executing its code. The "void" before the function name specifies that we wont be returning anything to the system once the application has finished. Note that the body of the function is denoted by braces.

04:   std::cout << "Hello, World";
This may look confusing, but it simply sends the text "Hello, World" to the standard output (which, by default, is the command prompt window). More information on how this works will be provided in the next part of this guide.

05: }
Finally, the "main" block is ended by a closing brace.

 
"Now I guess we're... 'Path-E-Tech Management'" -Dilbert

ShadowCaster

Possibly Insane

Registered
  02/01/2002
Points
  2203
19th April, 2004 at 07:59:24 -

ShadowCaster's Guide to C++
Part 2: Hello, Again


01: #include <iostream>

02: using namespace std;
Line 1 is exactly the same as in the first part of this tutorial, however we now have a new line of code directly below it on line 2. A namespace is a set of variables, objects and functions grouped so that they dont clash with any other variables, objects or functions you may create in your own application. By creating line 2, it moves everything from the "std" namespace into the "global namespace", so unlike the previous example where typing"std::cout" would output to the screen, by creating the global namespace you can just write "cout".

But doing this not only defeats the purpose of having a namespace in the first place, since everything becomes global, but it also increases the amount of memory required for your application. Although the amount of memory required is minimal, it is always a consideration when memory or performance is an issue for your software.

Even though everything becomes global, you do not need to worry about clashes if you import other classes from the standard C/C++ libraries. This is because most programmers will always globalise the std namespace for simplicity, so none of the libraries will create anything that clashes with the std namespace.

03: void main()

04: {
05: cout << "Hello, Again" << endl;
Lines 3 and 4 are exactly the same as the previous example, however this time the output line has changed slightly. As previously mentioned, the code now uses "cout" instead of the full "std::cout" command.

At the end of the line we now have a keyword (also from the std namespace) "endl". Including this will create a new line and flush the text so that it displays on the screen straight away (if this is not included, the line might not display straight away). Since this function is only one line long, this means absolutely nothing, but in large applications including this at the end is vital.

"endl", however, does impede on performace of the application since it needs to execute more lines of code. If you wish to include a new line, but not flush the output, you can use "escape characters". Escape characters are simply ways of entering special characters into your application using plain text. If you wish to print a new line you would write "\n" at the end of the line. Others exist such as "\t" (tab), "\\" (slash), and many more which arent too relevant at this stage.

You'll also notice that output using the "<<" operator is "stackable", that is, you can use it more than once on the same line. This is very useful, particularly in large applications, where you may want to print a string, then an integer, then a new line all at once, for example. Note, however, that you should concatenate strings using the "+" operator.

06: }
Like always, we close the block with a brace.

 
"Now I guess we're... 'Path-E-Tech Management'" -Dilbert

ShadowCaster

Possibly Insane

Registered
  02/01/2002
Points
  2203
19th April, 2004 at 08:02:38 -

ShadowCaster's Guide to C++
Part 3: String Input


01: #include <iostream>

02: #include <string>
03: using namespace std;
As with the previous examples, the iostream class is imported and the std namespace is made global. This time, another class is also being imported which will allow us to create and manipulate strings of characters.

Those of you who have a C background will be used to creating char arrays, however there is no benefit in using char arrays in C++ (any functions that require char array input can convert from a string quite easily using the c_str() function (i.e. char* myString.c_str()), however this is not important if you dont have a background in C).

04: void main()

05: {
06: string myString;
Lines 4 and 5 are the same in all the past examples; line 6 creates a new string called "myString".

07:   cout << "Please enter a string: ";

08: cin >> myString;
Line 7 outputs a message to the user asking them to enter something on their keyboard. Line 8 uses the cin object (within the std namespace) to retrieve a line of text from the standard input.

09:   cout << "You entered: " << myString << endl;
The final line of code stacks two strings (one a constant string, the other a variable string), followed by a new line, and sends it to the cout object to show the user what they have entered.

10: }
Lastly, the block is closed.

 
"Now I guess we're... 'Path-E-Tech Management'" -Dilbert

TheAlee



Registered
  27/02/2003
Points
  250
19th April, 2004 at 09:07:58 -

yay! C++ i'm learning it too... interesting tutorials, very basic, great for begginers!! coolio!

 
Alee is a Moo proggrammer and is a 3d graphics artist.

Tigerworks

Klik Legend

Registered
  15/01/2002
Points
  3882
19th April, 2004 at 11:39:19 -

Oh lord, no! It's int main()! NOT void main()! main() must return 0!

Um well, it's not really that big a deal, but main() is a function defined as being of type int. It's considered bad practice to use void main().

Image Edited by the Author.

 
- Tigerworks

TheAlee



Registered
  27/02/2003
Points
  250
19th April, 2004 at 12:09:23 -

i was wondering about that too, i always use int main () and what is std::cout? i just use cout...

 
Alee is a Moo proggrammer and is a 3d graphics artist.

ChrisB

Crazy?

Registered
  16/08/2002
Points
  5457
19th April, 2004 at 14:48:52 -

You only need to use std::cout if you're not using the namespace. (i.e. you didn't put using namespace std' at the top)

And void main() isn't that big a deal, it's not compliant but Windows doesn't complain.

 
n/a

Kris

Possibly Insane

Registered
  17/05/2002
Points
  2017
19th April, 2004 at 15:00:58 -

i prefer good old char arrays and printf

 
"Say you're hanging from a huge cliff at the top of mt. everest and a guy comes along and says he'll save you, and proceeds to throw religious pamphlets at you while simultaniously giving a sermon." - Dustin G

vortex2



Registered
  27/05/2002
Points
  1406
19th April, 2004 at 15:16:46 -

Here is a neat little example I made up becuase I was bored .


//include the stdio.h header file, used for printf and sprintf
#include <stdio.h>
//include the windows.h header file, used for the messagebox
#include <windows.h>
//define our "main" function with an integer return
int main()
{
//define a string variable called yourstring that is 255 characters long
char yourstring[255];
//write hi to the screen with a line break at the end
printf("hi\n");
//define a for loop, intialize our a variable with an int type, set the limit step to less then 10
//and set the stepping step to increase by 1 each time.
for(int a=0;a<10;a++)
{
//copies an interger to a string basically : "The number is: "+a
sprintf(yourstring,"The number is: %i\n",a);
//writes the string to the screen
printf(yourstring);
}
//opens a new messagebox that is not a child of any window, with the text of "A messagebox"
//a caption of "hello" , an exclamation icon, and an ok button
MessageBox(NULL,"A messagebox","hello",MB_ICONEXCLAMATION | MB_OK);
//same type deal except now its got diffrent texts, and a question icon, and yes/no/cance buttons.
MessageBox(NULL,"another messagebox","Heya",MB_ICONQUESTION|MB_YESNOCANCEL);
//we must return a value if we are using an integer type
return 0;
}

enjoy .

Image Edited by the Author.

 
A bit of insanity with every bite!

Shen

Possibly Insane

Registered
  14/05/2002
Points
  3497
19th April, 2004 at 15:43:00 -

"i prefer good old char arrays and printf"

rock on !!

 
gone fishin'

vortex2



Registered
  27/05/2002
Points
  1406
19th April, 2004 at 15:47:15 -

and yet another

//include the stdio.h header so we can use printf and scanf and sprintf
#include <stdio.h>
//include the string.h header so we can use strcmp
#include <string.h>
//define our main function
int main()
{
//defines our name string to be 255 characters long
char name[255];
//defines our result string to be 255 characters long
char result[255];
//prints "Please enter your name: " to the screen
printf("Please enter your name : ");
//asks us for some input and stores it in the name string
scanf("%s",name);
//copies the addition of "Hello"+name to the result string
sprintf(result,"Hello %s\n",name);
//prints the result string to the screen.
printf(result);
//if the name string is equal to the string "vortex"
if(strcmp("vortex",name)==0)
{
//then print "welcome master" to the screen
printf("welcome master\n");
}
//returns an integer
return 0;

}

.

 
A bit of insanity with every bite!

vortex2



Registered
  27/05/2002
Points
  1406
19th April, 2004 at 16:25:05 -

and the very last one for right now

//include the stdio.h header so we can use printf and scanf and sprintf
#include <stdio.h>
//include the string.h header so we can use strcmp
#include <string.h>
//include the stdlib.h header so we can use atoi,srand,and rand
#include <stdlib.h>
//included so we can use the time function
#include <time.h>
//prototype or DoGame function
void DoGame();
//define our main function
int main()
{
//prints "Vortex's Guess Game" to the screen
printf("Vortex's Guess Game\n");
//runs the DoGame function
DoGame();
//returns an integer
return 0;

}
//define our DoGame function with a void return type
void DoGame()
{
//define our Guess string with 255 characters (this is a local variable)
char Guess[255];
//define our Choice string with 1 characters (this is a local variable)
char Choice[1];
//define our ans integer (this is a local variable)
int ans;
//seed the random number generator to the time since 1970 lol.
srand ( time(NULL) );
//set the ans integer to a random value between 0-9 then add 1 to make it 1-10
ans=rand()%10+1;
//start a do while loop
do
{
//prints "Guess a number between 1-10: " on the screen
printf("Guess a number between 1-10: ");
//ask for user input and store it in the Guess string
scanf("%s",Guess);
//if the Guess string converted to an integer is greater then the correct answer
if(atoi(Guess)>ans)
{
//print "Too High" to the screen
printf("Too High\n");
}
//if the Guess string converted to an integer is less then the correct answer
if(atoi(Guess)<ans)
{
//print "Too Low" to the screen
printf("Too Low\n");
}
}
//if the Guess string converted to an integer is diffrent then the correct answer, repeat the while loop
while(atoi(Guess)!=ans);
//if the while loop has ended, then you entered the correct answer, so print "Correct" to the screen
printf("Corect!\n");
//prints "Play Again?(y/n): " to the screen
printf("Play Again?(y/n): ");
//asks for user input and stores it in the Choice string
scanf("%s",Choice);
//if you enter y
if(strcmp(Choice,"y")==0)
{
//call the DoGame function again
DoGame();
}
//else if you enter n
else if(strcmp(Choice,"n")==0)
{
//print "Ahh..." to the screen
printf("Ahh...\n");
}
//else if what you entered was diffrent
else
{
//print "next time follow directions..." to the screen
printf("next time follow directions...\n");
}
}


heh, its a simple guess a number game XP.

 
A bit of insanity with every bite!

ShadowCaster

Possibly Insane

Registered
  02/01/2002
Points
  2203
19th April, 2004 at 18:30:17 -

Yeah, I realise it's supposed to be int main() in good practice, however I made it void main() for the purpose of this tutorial since it's for beginners and I couldnt have been bothered to explain why, at this stage, you should return an integer.

Vortex: That's C, not C++. I dont know how you can prefer working with Char arrays, they're bloody annoying cos it takes more work if you want to define the size at runtime (i.e. with malloc and realloc).

Mike

 
"Now I guess we're... 'Path-E-Tech Management'" -Dilbert

vortex2



Registered
  27/05/2002
Points
  1406
19th April, 2004 at 19:05:06 -

does it really matter? C++ IS C..

 
A bit of insanity with every bite!

ChrisB

Crazy?

Registered
  16/08/2002
Points
  5457
19th April, 2004 at 19:09:58 -

std::basic_string is nice, but it'll never replace char* myString = new char[100];. Besides, if you want to do anything with Windows, you need char buffers for a lot of it.

 
n/a

vortex2



Registered
  27/05/2002
Points
  1406
19th April, 2004 at 19:58:59 -

here is a neat little thing that draws a bunch of randomly colored characters

//required for cout
#include <iostream>
//required for console functions, and RGB
#include <windows.h>
//required for string functions
#include <string>
//this really isnt needed but whatever....
#include <stdlib.h>
//required for time related functions
#include <time.h>
//need this for string type, and umm make sure you got this
using namespace std;
//prototypes the DrawColorString function
void DrawColorString(string szText, int X, int Y, WORD color);

//defines main function
int main()
{
//seed the random number generator
srand ( time(NULL) );
//defines character array with 1 character
char myStr[1];
//starts a for loop for the a variable 0-59
for(int a=0;a<60;a++)
{
//starts another for loop for the b variable 0-30
for(int b=0;b<30;b++)
{
//sets the character array at index 0 to random value
myStr[0]=rand()%255;
//calls the DrawColorString function to draw a character to the screen
//myStr is the character string
//a is the x position
//b is the y position
//sets the color to a random value
DrawColorString(myStr, a, b, RGB(rand()%255,rand()%255,rand()%255));
}
}
//goes to the next line
printf("\n");
//return a value
return 0;
}

//defines function to draw a colored string
void DrawColorString(string szText, int X, int Y, WORD color)
{
//defines the OutputH handle
HANDLE OutputH;
//defines the position Coordinate
COORD position = {X, Y};
//returns the handle of the console
OutputH = GetStdHandle(STD_OUTPUT_HANDLE);
//set the text color of the console
SetConsoleTextAttribute(OutputH, color);
//sets the position of the console
SetConsoleCursorPosition(OutputH, position);
//outputs the string value to the screen
cout << szText;

}


 
A bit of insanity with every bite!

Galaxy613



Registered
  29/01/2003
Points
  1765
19th April, 2004 at 20:10:04 -

erm...shads? I believe that WAS C++, I don't believe that

for(int a=0;a<10;a++){...

isn't vaild C; and I found out something neat:


#typedef STR char *
#include <stdio.h>

int main(){
STR name;

printf("Whats your name? "); scanf("%s",&name);
printf("\nHello %s!\n",&name);

system("Pause");

return 0;
}

pointers with typedef!

Image Edited by the Author.

 
Image
My forum: http://subsoap.com/ck/forums/index.php

ShadowCaster

Possibly Insane

Registered
  02/01/2002
Points
  2203
19th April, 2004 at 22:29:19 -

C definately isnt C++ [and vice versa], Vortex.

CK4RL: Who said anything about the FOR loop?

Mike ¿

 
"Now I guess we're... 'Path-E-Tech Management'" -Dilbert

vortex2



Registered
  27/05/2002
Points
  1406
19th April, 2004 at 23:49:10 -

C isnt c++ but c++ is based on c so c++ IS c.... and I use visual c++ 6.0 soo .

Image Edited by the Author.

 
A bit of insanity with every bite!

Kris

Possibly Insane

Registered
  17/05/2002
Points
  2017
20th April, 2004 at 14:28:02 -

using C++ doesn't mean you have to stick to its stupid new rules like having to use "cout" and taking the ".h" off headers ¬_¬

 
"Say you're hanging from a huge cliff at the top of mt. everest and a guy comes along and says he'll save you, and proceeds to throw religious pamphlets at you while simultaniously giving a sermon." - Dustin G

Galaxy613



Registered
  29/01/2003
Points
  1765
20th April, 2004 at 20:31:12 -

Kris is right

 
Image
My forum: http://subsoap.com/ck/forums/index.php

ShadowCaster

Possibly Insane

Registered
  02/01/2002
Points
  2203
21st April, 2004 at 02:47:49 -

Kris/CK4R1: You're absolutely right, you dont, but strange how I get shouted down for telling you correct syntax, yet just a few posts before I got in trouble for using incorrect but valid syntax (just like you did) myself... It's great how some people can have double standards, wouldnt you agree? ^__^

Mike

 
"Now I guess we're... 'Path-E-Tech Management'" -Dilbert

Tigerworks

Klik Legend

Registered
  15/01/2002
Points
  3882
21st April, 2004 at 03:10:39 -

C++ IS NOT C. C++ has a whole load more stuff like overloading, classes (with inheritence, encapsulation and polymorphism), exceptions, template classes, overloaded operators...

The string class is cool. Here's a snippet...

string MyStr;

MyStr = "Hello!";
MyStr += " What a nice " + "day";
cout<<MyStr.c_str();


To do that with char buffers you'd have a whole lot of strcats, strcpys and stuff, plus you run the risk of overrunning your buffer - the string class auto resizes to fit.

 
- Tigerworks

Assault Andy

Administrator
I make other people create vaporware

Registered
  29/07/2002
Points
  5686

Game of the Week WinnerVIP Member360 OwnerGOTM JUNE - 2009 - WINNER!GOTM FEB - 2010 - WINNER!	I donated an open source project
21st April, 2004 at 07:29:04 -

Very nice Shad, now people let's let him get back to writing more tuts.

 
Creator of Faerie Solitaire:
http://www.create-games.com/download.asp?id=7792
Also creator of ZDay20 and Dungeon Dash.
http://www.Jigxor.com
http://twitter.com/JigxorAndy

vortex2



Registered
  27/05/2002
Points
  1406
21st April, 2004 at 10:46:10 -

moo .

 
A bit of insanity with every bite!

Kris

Possibly Insane

Registered
  17/05/2002
Points
  2017
21st April, 2004 at 11:49:21 -

sorry if i sound [\write] like im shouting, I just think that people should be taught both methods then given the choice for themselves when they learn the pros / cons etc

 
"Say you're hanging from a huge cliff at the top of mt. everest and a guy comes along and says he'll save you, and proceeds to throw religious pamphlets at you while simultaniously giving a sermon." - Dustin G

Decal



Registered
  07/06/2003
Points
  1509

VIP Member
22nd April, 2004 at 16:13:36 -

I don't have a c++ editor.
What is the best c++ editor that it's free and downloadable?
And is there a downloadable trial version of Visual C++?

 
www.decal.rr.nu

Decal



Registered
  07/06/2003
Points
  1509

VIP Member
22nd April, 2004 at 16:13:37 -

I don't have a c++ editor.
What is the best c++ editor that it's free and downloadable?
And is there a downloadable trial version of Visual C++?

 
www.decal.rr.nu

Kris

Possibly Insane

Registered
  17/05/2002
Points
  2017
22nd April, 2004 at 16:49:24 -

Dev C++ is free. Dunno about MSVC demos though...

http://www.bloodshed.net/devcpp.html

 
"Say you're hanging from a huge cliff at the top of mt. everest and a guy comes along and says he'll save you, and proceeds to throw religious pamphlets at you while simultaniously giving a sermon." - Dustin G

Assault Andy

Administrator
I make other people create vaporware

Registered
  29/07/2002
Points
  5686

Game of the Week WinnerVIP Member360 OwnerGOTM JUNE - 2009 - WINNER!GOTM FEB - 2010 - WINNER!	I donated an open source project
23rd April, 2004 at 05:51:39 -

All you need is notepad and a compiler, but Visual C++ makes it easier by hilighting things and that.

 
Creator of Faerie Solitaire:
http://www.create-games.com/download.asp?id=7792
Also creator of ZDay20 and Dungeon Dash.
http://www.Jigxor.com
http://twitter.com/JigxorAndy

Decal



Registered
  07/06/2003
Points
  1509

VIP Member
23rd April, 2004 at 07:55:09 -

I hope it's better then "C++ Editor". That program is exactely the same as Notepad but it got a "C Language color engine" And has no compiler and i think i found a bug in that program. I can't save my work. I'm just waiting until Dev C++ is finished

 
www.decal.rr.nu

Klikmaster

Master of all things Klik

Registered
  08/07/2002
Points
  2599

Has Donated, Thank You!You've Been Circy'd!VIP MemberPS3 Owner
23rd April, 2004 at 10:15:19 -

I use DevC++
SolidSnake, if u use dev c++, make sure you have the line
   system("Pause");


before the end of the main function, or else the app will close automatically if u run it

 
n/a

Shen

Possibly Insane

Registered
  14/05/2002
Points
  3497
23rd April, 2004 at 13:38:10 -

I use Kate and gcc for mandrake it's like teh good, and free.

Image Edited by the Author.

 
gone fishin'

Decal



Registered
  07/06/2003
Points
  1509

VIP Member
25th April, 2004 at 15:41:26 -

Yeah i noticed it.
I opened the same app 10000 times at try to see how it works, but only got 0.001 second to see it.
So thanks for showing me the system("Pause"); part.
I try to read the "Guide to C Programming" help file. A lobg help file. The only problem is to remember the semicolon ; at the end of a statement. I always forget it and wondering why i can't compile. Shuld be a reminer when i click enter.

 
www.decal.rr.nu

Pixalatio



Registered
  16/03/2003
Points
  652
6th May, 2004 at 14:26:22 -

Visual C++ makes me add the .h on the end of header files or it says it cnt find them :S

 
Twas brillig, and the slivey toves
Did gyre and gimble in the wabe,
All mimsy were the borogroves,
And the momewraths outgrabe.

http://www.pixalatio.tk - visit me please

Did you know that your computer has secret buttons hiding behind others.

I intent to never delete any part of my sig until it is t big to handle.

for one small minute my rating was possibly insane

Mr Icekirby



Registered
  18/12/2003
Points
  846
6th May, 2004 at 17:09:00 -

c and c++ are so confusing, i prefere

start of level
>>shoot an object( "active" ) at speed 100

klik code is so much easier...

 
Mr Icekirby says so!
OBEY ME!

vortex2



Registered
  27/05/2002
Points
  1406
6th May, 2004 at 18:31:02 -

what would be your point by that? sure klick is easier but c++ is alot more powerful.

Image Edited by the Author.

 
A bit of insanity with every bite!

Tigerworks

Klik Legend

Registered
  15/01/2002
Points
  3882
7th May, 2004 at 08:29:42 -

How much C++ code would it take to make an eight directional movement object shoot a bullet and play an animation when you press spacebar?
In MMF it's 1 event.
In C++ - countless pages of source code.
And anyway, why spend all that time reinventing the wheel when it can be done so easily in MMF?

 
- Tigerworks

Batchman



Registered
  08/08/2003
Points
  231
7th May, 2004 at 11:24:13 -

C++ is a super thing called Object Oriented Language

the aim of this sort of language is to NOT TO RECODE THE SAME THING

so your 8 direction movement you will need 4 hour to do this , then you will only need 10 minutes

and now let's say :

how much MMF event would it take to make a platformer's AI which can move and jump with a platform pathfinding ?

 
n/a

Galaxy613



Registered
  29/01/2003
Points
  1765
7th May, 2004 at 12:24:35 -

8-direction in C++ MAY take serval pages, but if you make it felxable anuf then you can use it in other projects and it'll save you time.

 
Image
My forum: http://subsoap.com/ck/forums/index.php

Mr Icekirby



Registered
  18/12/2003
Points
  846
7th May, 2004 at 16:46:16 -

yes i know c and c++ are much more powerful, but here is where it becomes a problem i like to call me being lazy

 
Mr Icekirby says so!
OBEY ME!

vortex2



Registered
  27/05/2002
Points
  1406
7th May, 2004 at 19:36:01 -

well I am a newbie to c++ (extreme) newbie XP but still this is a thread about c++/c not klick.

 
A bit of insanity with every bite!
   

Post Reply



 



Advertisement

Worth A Click