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!
   

Post Reply



 



Advertisement

Worth A Click