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
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
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.
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
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
"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
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;
}
//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;
//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");
}
}
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
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.
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;
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
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
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
21st April, 2004 at 07:29:04 -
Very nice Shad, now people let's let him get back to writing more tuts.
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
"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
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.
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
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.
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?