CPPTUTOR

Embed Size (px)

Citation preview

  • 8/6/2019 CPPTUTOR

    1/13

    Turbo C++ Tutorial------------------By Ken Rockot

    Table of Contents-----------------Part 1. Introduction

    Part 2. Basic C++ Program StucturePart 3. Text StuffPart 4. User InputPart 5. Example Program #1Part 6. MathPart 7. ArraysPart 8. String VariablesPart 9. GraphicsPart 10. Example Program #2Part 11. Conclusion

    Part 1. Introduction

    --------------------All I really have to say here is make sure you understand Part 2 beforegoing any further. I'm probably not going to test most source code I putin here, so if it doesn't work, ask me about it. If you have any problemswith understanding this, or any other questions or anything, just ask meabout it. If you happen to see a function in a program that I haven'texplained in the tutorial, try looking at the Index under the Help menu inyour Turbo C++ editor. If you can't understand it by reading it's descriptionjust E-Mail me.

    To ask me crap, my E-Mail address is: [email protected]@aol.com

    I recommend that you send mail to my AOL name, because I don't check my

    Juno mail as often.

    Part 2. Basic C++ program structure-----------------------------------Alright. Hopefully, by the time you are done with this you might know C++

    well enough that you can do something pretty cool on it. Okay, first alittle about header files. A header file is a simple file that definesdifferent functions. Since you need a header file for just about every C++function, there is built-in command, #include. It would be used kinda likethis:

    #include

    Throughout this tutorial, several source code fragments will be shown togive a general idea of how you use a function or something. For most programsyou will ever make, you will almost definately use these three lines at thestart of your program:

    #include #include #include

    Those are the most important header files. They contain the majority of allC++ functions. Okay, now to start writing your first program. I stronglysuggest that you know QBasic, because if not, you will probably

    have no idea what I'm talking about a lot of the time. Every program'sbasic structure is first you have the included header files. Then, anyconstants, which are defined by #define. Say you want VAR to ALWAYS equal

  • 8/6/2019 CPPTUTOR

    2/13

    3 and not be changable (a constant), you'd simply type:

    #define VAR 3

    Another important note (and it IS important) is that C++ is case sensitive.All variables are case sensitive, so VAR is different from var, both of whichare different from VaR. Functions are also case sensitive. So be careful.

    After defines, any global variables (In QB, they're 'DIMmed' using DIM SHARED)are defined. I'll get into that later. Then, we have any functions tobe used in the program. Anyone who know QBasic should know about SUBs andFUNCTIONs. If you want to make a function (a SUB that returns a value), youwould define it as you would a variable. Then you have any parameters thatyou want passed to the function in parentheses, defined with int or whatever(more on defining crap later) Say you want a function called pointless toreturn the value of a number you give it, minus one:

    int pointless (int uservar){return (uservar-1);

    }

    Notice the ; at the end of the line. You need this at the end of everyline (well...most of them). This is helpful because unlike QBasic (ya know,the cheap, crappy, slow language), you can have multi-line statements, becauseonce C++ starts reading a line, it keeps reading until it hits a ;. Then itstarts again as a new statement. Any lines beginning with a # don't need a ;at the end.Also, notice the { and the }. Okay. Well, they are used for several

    statements. They are used for while, if, for, switch (like SELECT CASE), andany functions. In C++, there is no NEXT, END FUNCTION, END SUB, WEND, END IF,or END SELECT. When you use a command like for, if, while, etc..., You donot include a ; at the end of the if (or whatever other) statement. You just

    type that line, then on the next one, put a {. That specifies the start ofthe while, if, switch, or for clause. A } specifies the end. Anything onthe lines in between them are executed during that clause. There. Gladthat's over with.

    As for the main program, that's defined by:

    void main ( void ){

    }

    The { specifies the start of the program, and the } specifies the end.I always put all my functions that I make above the main program, becauseit's easier. You can put them below, but you just have to type more crap,so I recommend you don't. Oh, and another quick thing before I show you someexamples. To make a comment (In QB, it's '), use //. To make a multi-linecomment, start the comment with /* and everything after that will be a commentuntil C++ hits a */. Any comments appear dark gray in the main editor. Okaythese examples show stuff about some the stuff I've said so far:

    // A One-lined comment/* Amultiple-linedcomment */

    // Please note that if you run this program, you'll get absolutely no output.

  • 8/6/2019 CPPTUTOR

    3/13

    #include // May not use them all in this particular program,#include // but hey, what the heck?#include //

  • 8/6/2019 CPPTUTOR

    4/13

    printf ("Variable B = %d",B);

    If you want to use more that one variable in the printing, you just specifythem after the closing ", in respective order of what %d you want them toappear at, and seperate them with commas. Example:

    int A,B=3; //As shown with B, a var.'s value can be set while defining it.

    A=5;printf ("A = %d and B = %d.",A,B);

    Output:

    A = 5 and B = 3.

    Some other QBasic text-related statements can be quickly translated.

    QBasic: C++:

    LOCATE 5,6 gotoxy(6,5); (Row and column are reversed in C++)

    COLOR 15 textcolor(15);COLOR 1,3 textcolor(1);textbackground(3); (Background can only be 0-7)

    Some other C++ text-related functions:

    clreol(); Clear the current row without moving the text cursor at allclrscr(); Clear the text screen and move cursor to 1,1

    That about does it for the basic text stuff.

    Part 3. If/While/Switch/For---------------------------

    If:In QBasic, you use like IF a = 0 THEN PRINT a. In C++:

    if (a==0) printf("%d",a);

    I just put a ; at the end instead of using {} because only one thing happensin the statement. If you want to check to see if a variable = something,do not type: if(var=0) That will actually set a to 0 and then check if itis not equal to 0. It's hard to explain, so I won't, but just don't do it.You want to type: if(var==0).

    To use else in C++, close the if statement with a }. Then start the elsestatement followed by a {. Then do whatever and close it with a }.Example:

    if (b==0){textcolor(4);printf("b=0\n");

    }else{textcolor(3);printf("b!=0");

    }

    While:QBasic: WHILE var=0

  • 8/6/2019 CPPTUTOR

    5/13

    ...

    ...WEND

    C++: while (!var) //! is an abbreviation for NOT in C++{ //Like in QBasic not equal is . In C++ it's !=}

    If you know QBasic then you know what while does. Here's a small example inC++:

    int a=0;while (a

  • 8/6/2019 CPPTUTOR

    6/13

    In C++, you would do:

    int a=2,i=0;while (!i){switch (a)

    {case 0: //You need a colon there{printf("%d",a);exit(1);

    }break; //After the } to close a case statement, you need a break;.

    //Except on the last case statement of the switch.case 1:{printf("%d",a);a=0;

    }break;case 2:{printf("%d",a);a=1;

    }} //Close the switch

    } //LoopSince there is no DO...LOOP in C++, just do what I did there...Use while

    and have it loop until a variable does not = 0, but never actually change thatvariable, so it will loop forever.I think switch is also self-explanitory.

    In closing of this topic, I'd like to just quickly explain how to usecompound statements for if, while, etc. Here's some examples:

    QB: C++:IF a = 1 if (a==1)IF a = 1 AND b = 2 if ((a==1)&&(b==2))WHILE a = 0 while (!a)WHILE a = 0 OR b = 0 while ((!a)(!b))

    That basically just shows that means OR and && means AND.

    Part 4. User Input------------------Getting user input is not too complicated. Here, I'm just going to tell

    you some functions to get user input from the keyboard.

    kbhit(); If no key is currently being pressed, kbhit() = 0. If a key isbeing hit, it returns nonzero (usually -1).

    getch(); Like SLEEP, in that it waits for a key to be pressed, only itequals the key's character. For example, if you had the line:

    a = getch()

    and it was being executed, and you pressed w, a would thenequal w.

    scanf(format, variables)scanf is like INPUT, in that it you type all you want, until Enteris pressed. Format most likely will be "%d" or "%s" or a combo.

  • 8/6/2019 CPPTUTOR

    7/13

    It can be other things, though. Refer to your help file forC++ for more. Variables work like in printf.Here's an example:

    Code:

    int a;

    printf ("Enter an integer: ");scanf("%d",a);clrscr();printf("You entered %d.",a);

    Line of code being executed: scanf("%d",a);

    Program Output: Enter an integer:

    You type: 56

    Final Output: You entered 56.

    Not too difficult.

    That's enough for some standard input for now. Go try and make a programor something now. I bet you didn't realize it, but that's a lot of crap thatI've gone over now. Read the next part for a program that uses I thinkeverything, if not, most of the stuff I have gone over so far.

    Part 5. Example Program #1--------------------------/* The output of this program isn't really supposed to make sense, in case you

    were wondering. */

    #include #include #include

    #define const_var 100

    int global_variable_1;

    void Useless_SUB (int Useless_User_Input){int a=10;while (a!=0){a--;printf("a=%d\n",a);

    }printf("global_variable_1=%d\n",global_variable_1);printf("You inputed: %d\n",Useless_User_Input);

    }

    int Useless_FUNCTION (int Useless_Crap){int a;textcolor(15);textbackground(4);

    for (a=0;a

  • 8/6/2019 CPPTUTOR

    8/13

    printf("getch() is waiting...\n");getch();

    }return (1);

    }

    void main (void)

    {int i;i=0;clrscr();printf("Gimme a number: ");scanf("%d",i);clrscr();Useless_SUB(i);i=Useless_FUNCTION(4);printf("Useless_FUNCTION returned %d when 4 was passed to it.\n",i);getch();printf("Press any to use gotoxy to go to 1,1, then use clreol to clear line 1.

    \n");getch();gotoxy(1,1);clreol();getch();clrscr();printf("Press q.");i=0;while (!i){if(kbhit()){switch (getch())

    {case 'q':i=1;

    }}

    }printf("Okay.");printf("By the way, const_var = %d",const_var);

    }

    // End of program

    If you run that, you'll see a lot of crap that makes no sense. Just lookat the code. It's just to show how certain commands work.

    Part 6. Math------------The math in C++ is pretty simple. It works the same as in QBasic, except

    there are a few better ways of doing things. Some of this was explainedearlier, but I'll show it again. In QBasic, you can do something like:a = a + 5 or a = a / b. In C++, you CAN do it that way, but there is ashorter method. For thos same two examples, you could do:a+=5 or a/=b. That's simple. Also, a lot of times, like in a loop orsomething you might want to keep adding 1 to a variable or something likethat. Instead of doing a = a + 1, or even a+=1, you can do a++. a-- justsubtracts one. That's also simple.

    Here's a little table:

    Greater than: >

  • 8/6/2019 CPPTUTOR

    9/13

    Less than: =Less than or equal to:

  • 8/6/2019 CPPTUTOR

    10/13

    although 640x480 is still supported. There are, however, ways to make yourown BGI drivers, and there are drivers on the Internet for just about anyresolution or amount of colors. For now, we'll just use the highestresolution possible -- 640x480 - 16 colors. To use BGI, at least the BGIwe'll be using, you must copy EGAVGA.BGI into whatever directory you willbe running your program from. BGI stands for Borland Graphics Interface, bythe way. Okay. You first need to define a couple of variables. These

    variables will be used by initgraph. These will be the ones we use:

    int gr_mode=VGAHI, gr_drv=VGA, error;Then we make a call to initgraph:

    initgraph(&gr_drv,&gr_mode,"");

    NOTE: You will need to include graphics.h to use BGI!

    Now we need to check for errors:

    error=graphresult();if (error != grOk){printf("Graphics Error: %s", grapherrormsg(error));exit(1); //Exits program immediatly

    }

    There. You should be in 640x480 if all went well. Now for some graphicsfunctions. First I'll do simple QB -> C++ conversions.

    QB: C++:

    PSET (x,y),c putpixel(x,y,c);

    LINE (x1,y1)-(x2,y2) line(x1,y1,x2,y2);POINT (x,y) getpixel(x,y);LINE -(x,y) lineto(x,y)

    Other C++ functions:

    setcolor(color);Sets the current drawing color (usually for lines).

    moveto(x,y);Moves the current graphics cursor (used a lot with lineto) to x,y.

    closegraph(); You must use this to uninitialize the graphics and restorethe video mode to text mode.

    cleardevice(); Clears the graphics screen.

    getmaxx(); Returns the maximum x coordinate on the screen.

    getmaxy(); Returns the maximum y coordinate on the screen.

    getmaxcolor(); Returns the maximum available color.

    drawpoly(numpoints,pointarray);This draws a polygon on the screen. The polygon is not automatically closed

    so make sure the last point always equals the first point.Example:

  • 8/6/2019 CPPTUTOR

    11/13

    //Draws a green trianglepoint[0]=0; //Evens are x'spoint[1]=0; //Odds are y'spoint[2]=100;point[3]=100;point[4]=0;point[5]=100;

    point[6]=0;point[7]=0;setcolor(2);drawpoly(4,point);

    fillpoly(...);Same as drwapoly() except it fills it. Set the line color

    with setcolor and set the fill pattern and color with setfillstyle (explainedbelow).

    setfillstyle(pattern, color);Color must equal a number from 0 to getmaxcolor().

    Pattern must equal a number from 0 to 11. The patterns are explained below.

    Pattern # Description-----------+---------------------0 Empty1 Solid2 Horizontal lines3 ///4 Thick ///5 Thick \\\6 \\\7 Light hatch8 Heavy crosshatch

    9 Interleaving line10 Widely-spaced dots11 Closely-spaced dots

    setfillpattern(pattern_array,color);If you want to use your own pattern, use this instead of, not with,

    setfillstyle.Color must be a number from 0 to getmaxcolor().Patter_array is thme name of a user-defined string array which has a fixed

    length of 8. The 8 characters need explaining. First I'll give an example.

    char my_pattern[8] = { 170,170,170,170,170,170,170,170 };setfillpattern(my_pattern,4);

    That example will make the current fill pattern be verticle lines. Now weneed explaining. Each pattern consists of 64 pixels, 8 horizontally and8 vertically. Each seperate character in the string stands for a horizontalline in the pattern, giving us eight lines. A character can have a valuefrom 0 to 255. 255 in hex. is FF. In binary it is 11111111. If you look atthat binary number, you'll notice that 255 (the maximum value for a character)in binary is 8 digits. Usually, you'll need a calculator to make a pattern.170 in binary = 10101010. Therefore, if we put 8 170's in my_pattern, we willhave:

    10101010

    101010101010101010101010

  • 8/6/2019 CPPTUTOR

    12/13

    10101010101010101010101010101010

    Anywhere where there's a 1 is where a pixel, of the color you set, will beplaced. Any 0's will be a pixel of the background color (defaulted to black).

    Say you wanted diagonal lines like \\. Get a calculator. Okay. The firstline should look like:10001000Set your calculator to binary mode and enter 10001000. Convert that toa decimal number. You get 136. There's your first character. Here's therest:

    Binary: Decimal:

    Second: 01000100 68Third: 00100010 34Fourth: 00010001 17Fifth: 10001000 136

    Sixth: 01000100 68Seventh: 00100010 34Eighth: 00010001 17

    Therefore, you could now make a pattern like this:

    char cool_pattern[8] = { 136,68,34,17,136,68,34,17 };

    That would be \\.

    setpalette(color1,color2); Sets the attributes of color1 to those of color2.Example: setpalette(1,15);That makes color 1 bright white instead of blue.

    There are other methods of doing better, faster graphics, but they requireimplementations of the Assembly language into your C++ program. Since thisis not a graphics tutorial, I won't cover how to make your own functionsto set the screen mode to 320x200 - 256 colors, and the functions to setpixels and the palette in this screen mode. It also does it without theuse of BGI. If you would like a tutorial on that stuff, E-Mail me yourrequest (See Part 1. Introduction for E-Mail address). If I get enoughrequests, I'll make one. As for now, though, that's enough for graphics.

    Part 10. Example Program #2---------------------------//This program just does some stuff with graphics#include #include #include #include

    #define NUM_PIXELS 10000#define NUM_LINES 5000

    void main (void){int Gr_Driver=VGA, Gr_Mode=VGAHI, Error_Code;initgraph(&Gr_Driver, &Gr_Mode, "");

    Error_Code=graphresult();if (Error_Code != grOk){

  • 8/6/2019 CPPTUTOR

    13/13

    printf ("Graphics Error: %s", grapherrormsg(Error_Code));exit(1);

    }cleardevice();int i;randomize();for (i=0;i