|
Post by Admin on Jun 29, 2015 12:57:22 GMT
Write your own C++ programs and applications.
|
|
|
Post by handsomepredator on Jun 29, 2015 13:01:05 GMT
ADDITIONAL NOTE_tutorial
ADDITIONAL NOTE
All C++ commands and keywords like int, cout and return must be typed using lowercase letters. If you use uppercase letters, the C++ compiler will not compile the program. You will have to correct the error first. wink.gif
|
|
|
Post by handsomepredator on Jun 29, 2015 13:01:20 GMT
c++ input_tutorial
#include <stdio.h>
main {
int yb, py, age;
printf("Present Year: "); scanf("%d", &py);
printf("\nYear of Birth: "); scanf("%d", &yb);
age = py - yb; printf("\nUr age is: %d", age);
getch(); } getch(); function - It's function is to wait for the user to press any key on the keyboard. When it does, it passes back the key that was pressed.
Take the getch(); line out of a program. Compile & Execute. What happens? Do you see the results?
Put the getch(); line back again. Now you can see why we need it there to stop the window from closing before we have finished with it. The computer waits at the getch(); function until a key is pressed, and only then does the program continue with the next instruction. There is no next instruction, so the program ends.
%d - integers %f - float %c - single character %s - series of characters printf - for output scanf - for input
Use clrscr(); if you want to clear the screen.
|
|
|
Post by handsomepredator on Jun 29, 2015 13:01:32 GMT
C++ STATEMENTS_tutorial
C++ STATEMENTS
Finally, the statement sum=x+y; computes the sum of x and y and stores it in a variable sum. This is an assignment statement. Note that an executable statement in C++ must be followed by a semicolon (wink.gif.
|
|
|
Post by handsomepredator on Jun 29, 2015 13:01:54 GMT
C++ TUTORIAL001
C++ TUTORIAL
a tutorial on C++. I hope this helps.
Quote Lesson1: Hello world! ~
Nearly every programming language tutorial starts with a "Hello World" program. Well, lets start with that, but explain it completely.
#include <iostream.h>
int main() { cout<<"Hello, World!\n"; }
Compile the above program and congratulations! You're a C++ Programmer!!!! You've made and compiled your first program!!! Now, lets examine this program:
Line 1:#include <iostream.h>
"#include" tells the compiler to take the file "iostream.h" and make the functions in it ready for use. Anything in C++ that starts with "#"(pound symbol) is called a "preprocessor directive". What is a preprocessor directive, you ask? First off, the preprocessor is a thing the compiler does before reading the code. Now, you might know what iostream.h does, but if you don't, it defines all the functions required for input/output. You see "cout"? That is one of them. "cout" is what you type to tell the compiler that everthing following the "<<" is to be printed to the screen. The "<<" is there to take everthing following it and do the "cout" function on it. It is required for cout to work correctly. The "<<" are directives telling that take the following information and do all the functions of cout on it.
Line 2:(blank) In C++, spaces and returns are not required. You can take out the spaces and returns in this program and it will run correctly. But, you can't take out all the spaces and returns. You need them for certain things. Here is a very brief list:
*Spaces must be between a variable name and the data type (we'll talk about those a little later) *A return must be after any preprocessor directive (again, we'll talk about that later on) *The "no spaces/returns" rule does NOT count for quotes. You type things in quotes exactly how you would write it on paper.
And many more will be covered as we go on. If you feel confused now, don't worry. I will cover everything I talked about so you know and understand everthing.
Line 3:int main() This probably looks confusing if you know nothing of C++, so let me explain. "main" is a *required* function in every program. If you don't have it in your programs, the compiler will have an error and it won't compile. That is because "main" starts the program's operations. It can be anywhere in your program, but it must be there. Think of it as the script of the program, in that it has the order and rules to run the program. If you have multiple functions, you call them all from main in the order that you want them to happen. For example, here is a program with 2 functions, but main calls the second function:
#include <iostream.h> void multiply(); //If there are multiple functions other than main(), you MUST declare them at the beginning of the program
int main() { cout<<"An example of multi function programs!\n"; multiply(); }
void multiply() { cout<<"2*2=4"; }
You see how important main() is? "multiply" would never happen if it is never called, so since no other function is calling it, main() calls it and it does the contents of "multiply()". Now about the "int": "int" means that the function has a return. You can also use void, but this is not ANSI standard, so you may not use void with main(), because main returns 0, ending the program. There is a line in C++ that tells the compiler when the program has stoped and finished. It is NOT required, but it won't hurt to add it. It is written as "return 0;". Thats the return that I am talking about. The "0" means that the program has finished executing, and the application ends. The application is still open, but there is no more commands to do. Most ANSI compilers, like Dev C++, put the line in by itself, so that is why it is not required. We'll talk more about "int" a little later on. But for now, thats how it works. The parentheses are used with nearly every call in C++, and they are there to tell the program what variables to carry with it. The stuff that goes in the parantheses are called "arguments". You shouldn't worry, as they are really just for more advanced C++.
Line 4: { This is what you write to say that the function is going to execute. It starts the function, and it starts executing until the end bracket is reached.
Line 5:cout<<"Hello, World!\n"; As described above, "cout<<" is how you output something to the screen. Everything after the "<<" is printed to the screen. So here, the quotes are taken out, as they just hold the text to print, and Hello, World! is printed to the screen exactly like that. Now, what about the "\n"? "\n" is one of the "escape commands", or a command that does something simple to the text. In this one, "\n" is used to tell the program to skip to the next line and continue from there. The "\n" is not printed, as anything that starts with "\" in quotes is considered an escape command. Here is a list of alot of them:
\n --Skips to the next line and continues from there \t --Does what the "tab" button does. It indents about 3 spaces. \\ --It prints a "\" to the screen \' --It prints a single quote to the screen \" --Prints a double quote to the screen
This is all that will be used often by you. Memorize it because it is used quite often. Finally, that ";". That is used whenever a single command is executed. Here, the text has been printed so we put that there to tell the compiler that command has finished. It is required.
Line 6: } Ending bracket. It ends the function.
There! You have completed the introduction to the world of C++! Feel proud because you are one step closer to becoming a great programmer!
|
|
|
Post by handsomepredator on Jun 29, 2015 13:02:09 GMT
C++ TUTORIAL002
Lesson 2: Loops And Conditions
Quote We are going to learn that programs run in one big loop. Every program begins in a loop, and branches off to smaller loops, and smaller, etc. We will begin studying what kind of loops C++ support, practice when and when not to use certain types of loops, and find common mistakes. All that great boolean algebra we learned will yet appear again as we learn how to control our loops!
C++ supports these types of branching mechanisms: if if..else if..else..if switch..case..default
C++ supports these types of loops: for while do..while
You can make decisions using these special operators: Less-than < Greater-than > Less-than or equal to <= Greater-than or equal to >= Equal to == Not equal to !=
We will use these operators in making decisions to what the program should do next. These set of operators are called "Rational and Equality Operators" and compare the value on the left to the value on the right. These evaluate to a bool value which is true or false.
Example 3.1.1 bool equal = (5 < 3);
the variable equal gets assigned the value false because 5 is defined to be greater than 3 by our math system.
Section 3.2
The most simplest form of control loop is the if keyword. The syntax for this keyword is as follows:
if ( expression ) statement1 else statement2
The if keyword executes statement1 if expression is true (nonzero); if else is present and expression is false (zero), it executes statement2. After executing statement1 or statement2, control passes to the next statement.
Example 3.2.1 if ( i > 0 ) x = y / i; else x = 0;
In this example, the statement x = y / i; is executed if i is greater than 0. If i is less than or equal to 0, x is assigned the value of 0. Note that the statement forming the if clause does not end with a semicolon. Note that again so you don't forget.
Let's look at a more complex example where we want to do more than one statement depending on how if the if clause evaluates.
Example 3.2.2 if ( i >= 5 ) { x = 4 * i; i++; } else i = 5;
In this example, the statements x= 4 * i; and i++; are executed if i is greater than or equal to 5. If i is less than 5, i is assigned the value 5. Note that how we grouped our statement in braces { } to indicate two or more statements that need to be executed if the if clause evaluates to be true (nonzero).
Now the else clause does not need to be included if you don't have any optional functionality you need to be performed. It is perfectly legal to do this:
Example 3.2.3 if ( i >= 5 ) { x = 4 * i; i++; }
Example 3.2.4 But what if we wanted to evaluate many cases? We will have to use a nested if..else..if statement to accomplish this. Let's say we wanted to perform a separate action when i is 0, 1, 2, 3, 4, 5. This is how it would be coded: if ( i == 0 ) x = 1; else if ( i == 1 ) x = 2; else if ( i == 2 ) x = 4; else if ( i == 3 ) x = 8; else if ( i == 4 ) x = 16; else if ( i == 5 ) x = 32;
If i is 0, x is assigned 1, then control jumps to the end of our if clause. If i is 1, x is assigned 2, then control jumps to the end of our if clause. If i is 2, x is assigned 4, then control jumps to the end of our if clause. If i is 3, x is assigned 8, then control jumps to the end of our if clause. If i is 4, x is assigned 16, then control jumps to the end of our if clause. If i is 5, x is assigned 32, then control jumps to the end of our if clause.
For you math gurus out there, can you see what is happening to x depending on the value of i in Example 3.2.4? If anyone noticed the simple pattern, you would see we are calculating the powers of 2, using i as our exponent. We will go back to this example many times and show you different methods of doing this.
Section 3.3
Now just imagine if we wanted to get the answer of 2 to some variable, which is i, in C++. C++ does not have an exponent operator, so we would have to have to have huge and ugly code like Example 4 in Section 3.2. Fortunately, we can loop to find answers to complex problems like the 2 to the i-th power. This brings us to our third new keyword in our lesson. The for keyword has the syntax as follows:
for ( init_expr; cond_expr; loop_expr ) statement
For even a simpler syntax of the for loop, remember this:
for ( step1; step2; step4 ) step3;
Wow! This is alot to digest, so lets break apart each expression and look at each one individually:
1. The first thing that happens when a for loop is encountered is the init_expr expression is evaluated. init_expr is most commonly used to initialize a variable which will control the loop. 2. Next cond_expr is evaluated. This expression is a conditional expression, which determines if the loop will continue going or not. If cond_expr evaluates to true (nonzero), the loop continues. If cond_expr is false (zero), control passes to the statement following the for loop. 3. statement is executed. 4. loop_exr is than evaluated, and goes back to step 2.
Notice that after loop_expr there is no semicolon!
Example 3.3.1 int x = 1; for ( int i = 1; i <= 10; i++ ) x *= 2;
Let's go through the steps of this for loop: 1. First the i variable is created and initialized to 1. 2. Next i <= 10; is evaluated next. Since i is 1 and is less than 10, it evaluates true and we enter the loop and execute x *= 2;. 3. Next we increment i with our loop expression, i++;. 4. Next i <= 10; is evaluated next. Since i is 2 and is less than 10, it evaulates true and we enter the loop and execute x *= 2;. 5. Next we increment i with our loop expression, i++;. 6. We continue this process until our conditional expression, i <= 10; evaluates for false, and we exit the loop. This happens when i increments to 11.
Look at what we did! We just compacted that ugly if..else..if clauses into a for loop and we got the value of 2 to the 10th power, which is 1024! Now that surely beats the latter.
Example 3.3.2 But say we didn't wanted to calculate 2 to the 10th power, we wanted to calculate 2 to the nth power? We could go back and modify the example as follows: int x = 1; int n = 5;
for ( int i = 1; i <= n; i++ ) x *= 2;
Remember that when you do programming wi // th integers, the int data type can only hold 16-bits or 32-bits (or even 64-bits) depending on what bit compiler you use. So if we are using a 32-bit compiler, n being set to 19 would be safe because we have 32-bits (0 through 31) to work with. If we were working on a 16-bit compiler, 19 would overflow us and x would be complete junk to us.
Remember our "bug" term from the last lesson? This unexpected overflow is one type of bug which can make a program spit out junk, even though the logic and the program is perfectly fine. Watch out for sneaky things like this.
Section 3.4
Usually the for loop is used when we want to iterate through a list of numbers. In Example 2 of Section 3.3, we went from 1 to n. Sometimes there is nothing to iterate and just want to keep on looping while a condition is true. This brings us to the next kind of loop, called the while loop. The syntax for while loop is as follows:
while ( expression ) statement
The while keyword executes statement while expression is true (nonzero).
Example 3.4.1 bool p = false; int x = 0;
while ( !p ) { x++; p = (x > 20); } x++;
This while loop does not terminate until p becomes true. When p is true, the expression !p evaluates to false, terminating the loop, then increments x one last time.
The variable p that controls this loop isn't very good at describing what it does. Welcome to the world of good variable names! You have became advanced enough to give good variable names. This has many advantages like not having to guess at what a variable does. This is a much better example:
Example 3.4.2 bool IsXGreaterThan20 = false; int x = 0;
while ( !IsXGreaterThan20 ) { x++; IsXGreaterThan20 = (x > 20); } x++;
Going back to our "2 to the n-th power" example, we can use a while loop to do the same thing as the for loop did. (The for loop is more appropriate for this kind of situation, so you should stick with that). Just remember these two simple rules: 1. Use for when wanting to iterate a range of values. 2. Use while when you want to loop while a condition is true.
Example 3.4.3 int x = 1; int n = 5; int i = 1;
while ( i <= n ) { x *= 2; i++; }
Section 3.5
Sometimes, it might not always be appropriate for a loop to test its condition at the beginning of the loop, like the while loop. If you want to enter the loop and then check at the end, we use the do..while loop. The syntax for the do..while loop is as follows:
do statement while ( expression );
This works just like the while loop, except the evaluation of the expression comes at the end. This kind of loop ensures the statement will be executed at least one time. Therefore, we do not need to go in-depth on this section.
Example 3.5.1 int y = 0; int x = 10;
do { y = x + 5; x--; } while ( x > 0 );
The loop is entered. then y gets added x + 5, then x gets decremented. This loop continues running until x is no longer greater than 0. So y gets added 15, then 14, 13, 12, ... until 6.
Section 3.6
The last and final control statement in C++ is the switch..case..default trio. This is the syntax:
switch ( expression ) { case constant_expression: ... statement ... default: statement }
We use this when we want a more readable form of an if statement. constant_expression must be an int value like 2, 3, -6, but not a variable or a floating point number. It cannot be a variable because as the word implies, it varies. It cannot be a floating point, because computers can't represent fractions perfectly, which would mess up the case.
A case is just like if the code read, if ( expression == case ), but much more readable. You can think of default: as being the else clause also.
Example 3.6.1 Watch how we convert the if clause to the switch clause: if ( x == 2 ) i = 1; else if ( (x == 3) || (x == 5) || (x == 7) ) i = 2; else if ( (x == 4) || (x == 9) ) i = 3; else i = 4;
can be transformed into switch ( x ) { case 2: i = 1; break; case 3, 5, 7: i = 2; break; case 4, 9: i = 3; break; default: i = 4; }
Now isn't that much easier to understand? Notice the break; statement. This "breaks" us out of the switch clause and we continue execution outside of it. If we did not have break;, the next statement would keep on executing until it hits the ending right brace }.
Example 3.6.2 Here is an example of the problem stated above: switch ( x ) { case 2: i = 1; case 3, 5, 7: i = 2; default: i = 4; }
Oh no! if x is 2, then it will assign i to 1, then 2, then 4! We don't want this, so we must put our break; statement in there to prevent this from happening. This is another peculiar bug which can creep into your code.
|
|
|
Post by handsomepredator on Jun 29, 2015 13:02:37 GMT
C++ TUTORIAL003
FUNCTIONS
Quote We will now see the usage of functions in C++. Functions are very useful if you desire to use a particular set of statements or a particular operation again and again. With the help of a simple example i will explain the concept of functions.
The general form of a function is
return-type function-name (parameter 1, parameter 2)
{
}
return-type -> Its the value that the function will return after various calculations.
function-name -> This is the name of the function that we like to use
parameter 1 -> This is also called as the argument. These are the variables that are being passed on to the function
parameter 2 -> Another variable that is passed to the function
I will illustrate the use of functions with the help of the following example
#include<iostream.h>
int add(int x, int y)
{
int z;
z=x+y;
return z;
}
void main()
{
int a=3,b=5,c;
c=add(a,cool.gif;
cout<<"The sum is "<<c;
}
Let us see how the code works
int add(int x, int y)
{
int z;
z=x+y;
return z;
}
In the above code segment 'add' is the function name and 'int' is the return-type.
There are two parameters 'int x' and 'int y'.
The variable int z is used to store the sum of the two numbers.
As mentioned before,
return z;
the integer z is returned back.
Ok but where does the terms 'calling' and 'returning' the values arises? We will see that...
In the main section you will be able to the lines
int a=3,b=5,c;
Here we are declaring (and initializing) a and b and declaring a variable c.
Consider the following line:
c=add(a,cool.gif;
At this point the function gets 'CALLED'. The function 'add' is called with two parameters 'a' and 'b'. It is said that the integers a and b are passed to the function 'add'.
When the function is called the program control is transferred to the 'add' function. The two parameters a and b are added and 'RETURNED' through the variable 'z'. This variable is stored in 'c' and then printed.
This is how functions work in C++ and any other language. This is just one way of using functions and you will know more as you proceed.
|
|
|
Post by handsomepredator on Jun 29, 2015 13:02:50 GMT
C++ TUTORIAL004
FILE STREAMING [/color][/b][/glow]
Quote INTRODUCTION --------------- To a fledgeling c/c++ programmer ,the language might appear incredibly criptic and idiomatic.The language allows coding styles with levels of pointers,indierction and abstraction.The ground between the novice stage and fluency stage can only be traversed through the experience of writing C++ programs and discovering through practice the true power and sensible philosophy behind C/C++'s features and even its ommisions.
The main point is that it is not suffcent to know just the syntax and operations.Instead it is your perception of how the different features and elements of the language interact with one another,with the environment and with the design to accomplish pedestrian,but essential tasks with the elagance and power (for which c/c++ is famous) that counts. What i have tried here is to cover the basic c++ functions and features.This tutorial is not a theoritical blah blah,but a practcal and simple illsustration c++'s features. Also I have chosen a 16-bit compiler Turbo c++ ver 3.0 coz a typical 32-but compiler offers so many features that a begginner is likely to feel lost.But this tutorial is not for absolute begginers ,a knowledje about the following is expected 1)data types and programming constructs 2)basic idea of class No need to know anything about pointers!.
First Things First...................... ______________ First thing to do is to include the header file fstream.h like this...#include<fstream.h> 2)next thing is to declare the stream object example fstream skuddy; 3)third thing is to use open method to initialize it skuddy.open("filename",filemode); where filename stands for a valid file location & filemode for the below ios::in -open for input ios::out-open for output ios::binary-open in binary mode ios::app-open for appending ios::nocreate-do not create the file if it does not exist ios::noreplace-ditto,do not replace(if the file exists) ios::trunc-destroys data in existing file
phew! thats it. u can input & output as shown in the following program
#include<fstream.h> #include<conio.h> void main() { int n; fstream skuddy; skuddy.open("inter.txt",ios::out); cin>>n; skuddy<<n; skuddy.close();
}
now read inter.txt with a text editor u will find an integer value similaly u can output as..
#include<fstream.h> #include<conio.h> void main() { int n; char ch; fstream skuddy; skuddy.open("inter.txt",ios::in); skuddy>>n; cout<<n; getch(); skuddy.close(); }
finally invoke the destructor as skuddy.close();*/ BASIC FUNTIONS ---------------- This section deals with the most common funtions used in file i/o. eof() ----- prototype:int eof(); This is funtion is primarily invoked when you need to test the end of file.As this example illustrates fstream skuddy : : : while(!skuddy.eof()) { //do something }
CHARACTER I/O --------------- The prototypes of the funtions are as follows.Do not worry if u do not understand the bluff,it will be clear as you proceed with the examples get(),put(),getline() --------------------- istream & get(char ch); istream & get(char *buf,int num,char delim='\n'); ostream & put(char ch); istream & getline(char *buf,int num,char delim='\n'); The getline function is used for reading strings as in the following code snippet #include<fstream.h> #include<conio.h> #define max 80 void main() { char buff[max]; fstream skuddy; skuddy.open("win.doc",ios::in); while(!skuddy.eof()) { skuddy.getline(buff,max); cout<<buff<<endl; }
getch(); skuddy.close();
}
put()&get() functions are used to output and input single character at a time as shown in the following code snippets #include<fstream.h> #include<string.h> void main() { char st[]="Time is a great teacher, but unfourtunately it kills all its pupils"; fstream skuddy; skuddy.open("file.txt",ios::out); for(int j=0;j<strlen(st);j++)skuddy.put(st[j]); } // read file.txt with a text editor #include<fstream.h> void main() { char ch; fstream skuddy; skuddy.open("file.txt",ios::in); while(!skuddy.eof()) { skuddy.get(ch); cout<<ch; } skuddy.close(); } OBJECT I/O ----------- Since c++ is an object oriented language it allows u wirte & read objects to disks.The functions used are read and write.The snippets given below will make it clear.
#include<fstream.h> class emp { char name[40]; int id; public: void getdata() { cout<<"Enter name:"; cin>>name; cout<<"\n Id :"; cin>>id; } }; void main() { emp e; e.getdata(); fstream skuddy; skuddy.open("emp.doc",ios::out); skuddy.write((char*)&e,sizeof(e));//write the object to disk skuddy.close(); }
#include<fstream.h> #include<conio.h> class emp { char name[40]; int id; public: void displaydata() { cout<<name; cout<<"\n"<<id; } }; void main() { emp e; fstream skuddy; skuddy.open("emp.doc",ios::in); skuddy.read((char*)&e,sizeof(e));//read from file and put it to e e.displaydata(); skuddy.close(); getch(); }
Difference b/n text and binary files ------------------------------------ Text files treat all the data u enter as text.For eg it treats even space,line feed and even numbers as text.As a result more space is taken up,but it would as render the file more readable.
Binary files treat the data as a sequence of bytes.This method is used by put(),get(),read(),write().As a consequence if u read the files wriien using put() etc what u get is a heap of gibberish!. File Pointers ------------- Here the term ' pointer' has a different meaning,basically a file is associated with 2 pointers namely the1)get pointer(current get position)2)put pointer(use ur imagination!) meant for finer control of file i/o.The seekg() and tellg() functions help you to work with the get pointer and the seekp() and tellp() for the put pointer.I will demostrate use of the these functions using some examples eg infile.seekp(-30,ios::end); will put pointer to 30 bytes before the end of the file and infile.seekp(10,ios::beg) will put pointer to 10 bytes from the beggining of the file. tellp() returns the current position of the put pointer.Similarly we can set and examine get pointer by means of seekg() and tellg().
Final Words ----------- File I/O is a serious and extensive topic,what i have covered here is the bare minimum.I havent even scratched the surface of file i/o.But if u a have gained a solid understanding of what is given here it will help you a lot!.I believe that since you have taken the pain to go through this document,you are quite interested in c/c++ file i/o.Nevertheless I think that sooner or later you will emerge as a powerfull C++ programmer!.Also feel free to contact me,i ,m 18 yrs old-ask me all sorts of doubts. Any errors and ommisions are due to my pigheadess ,which i will try to rectify if you send it to s19@swissinfo.org Or a99@swissinfo.org.
It will help a lot if you try to work out the following assignments
Assignments ------------ 1)a simple adress book manager 2)a simple file encription program 3)a simple 16 bit bmp & pcx reader 4)learn about windows programming and grasp the concept of serialization etc For more advanced fellows-5)Try to figure out how a file system is implemented --Oh Boy,i am getting more and more nerdy! Still to come ----------- 1)file operations in c/c++ 2)tutorial on pointers 3)on asm 4).....depends
|
|
|
Post by handsomepredator on Jun 29, 2015 13:03:10 GMT
C++ TUTORIAL005
Creating User-Defined Header Files
Quote It is important to note that I am using Dev-C++ V.4 as the compiler for all information depicted in this tutorial. Let me start this topic off by first explaining what a header file actually is. Everytime you write a program you have to specify certain #include statements at the beginning of your program. Why is this? Basically, the #include statement is actually a link to a header file containing pre-defined elements that you will need to use for successful execution of your program. Header files are created so you can use the code contained in them in multiple programs without having to write the code everytime you want to use it in a program. It is all pre-defined in a seperate header file so all you have to do is "include" it in your program.
Take the iostream.h header file for example. Load your compiler and open iostream.h . Peek at what it contains. Do you understand it? Can you figure out what some of it is doing? Probably not at this point, but you should be able to recognize certain function calls and declarations. What you see is actually code used to define the standard input/output streams. By using this header file in your programs, you have access to the input/output streams. Without this convenient header file, if you wanted to have access to the input/output streams, you would first have to define them. Very tedious and time consuming not to mention the extra effort of learning how to define them.
A user-defined header file is a header file that you, as the programmer, create. --> iostream.h and all other header files which are "included" using angle brackets are pre-defined and are provided for by the makers of the Dev-C++ compiler. For example, #include <time.h> and #include <winbgim.h> (notice the brackets). When you create a header file, which I describe below, and "include" it in your program, you will use quotes instead of brackets. For example, suppose guess.h is a header file that you created for a program. You can include this header file in your program by using: #include "guess.h".
For the most part, user-defined header files are used to define constants, user-defined types, and to list function prototypes to be used in a main file. NOTE: header files do not include function definitions --> they will go in a seperate "auxillary" source file that will have a (.cpp) extension. Also note that you shouldn't compile header files individually. There is no need to do this. The header files will be compiled when you compile the actual program which tries to link to it. Also, when you compile the actual program, the only elements in the header file which will be compiled are the elements in which the program will need to use.
The following explains what is required to create a header file using Dev-C++ V.4 compiler:
First, open a new document and clear it. Next, enter the following information (I describe the elements further below):
#ifndef __NAMEOFHEADER_H #define __NAMEOFHEADER_H
// place constants here
// place user-defined types here
// place function prototypes here
#endif
Notice the (#) symbol preceding commands in the above file. Anytime the (#) is used, it is associated with the compiler directories. It tells the compiler to do something as in turning on/off some compiler setting. It is not an executable statement. It only functions during compilation. NOTE: in the above code, NAMEOFHEADER is the name of the header file; this name can be anything you want it to be, but it should be descriptive and reflect what it actually functions to do.
The #ifndef command can be read as "if not defined" which means it checks to see if a given symbol is defined or not. If the symbol is not defined, compilation will move into the body of the header file and do necessary definitions. If the symbol is defined, the header fill will not need to perform definitions. The #define is only performed if #ifndef returns a value of true, which means the symbol is not defined. #define literally does what it reads: it defines the elements contained in the header file for use in the program which called upon it. Basically, these two commands, especially #ifndef , gaurd against re-declaration errors if the header file is included in the calling program more than once. In a single application, you may be using multiple source files, and it is possible that more than one of the source files may try to #include the same header file.
Generally speaking, when you create a header file that contains the constants and prototypes for a program, you will also want to create an auxillary file (will have a .cpp extension) that holds all of the function definitions to be used in the program. This means that the only function in the main program will be the main() function. The question may arise as to how the compiler will know how to link the auxillary file to the actual main program file. This can be done through the use of a project file. It is important to note that the main program file, which contains the main() function, and the auxillary file, which contains the function definitions, both have to include the user-defined header file and also any other compiler directives they use. When you include a user-defined header file, you have to use double quotes instead of using brackets. The brackets tell the compiler that it is dealing with pre-defined include files and the quotes tell the compiler it is dealing with a user-defined header file. For example, if I create a header file called myHeader.h, I can include it by using #include "myHeader.h".
Creating Project Files In order for you to successfully link all of your source files (main file and auxillary file), you will have to create a project and place the files in it. Project files are used to "tie together" mulitple source files into a single executable application or program. Creating a project is extremely easy. The following explains how to create a project using Dev-C++ V. 4 compiler:
If the individual source files already exist, which means you have already created them, click the file menu and select new project. For dos level programs (probably what you want), at the next prompt select console application and make sure C++ project is selected. At the dialog box, enter a descriptive name for the project, which will be given an extension of .dev. It is important to note that none of the source files can have the same base name as the project file. The base name of project will be used as the name of the executable file that is created after successful compilation. Next goto the project menu and select add to project. At the open prompt, select all of the source files to be included in the program (NOTE: do not include the header file itself). Now, you should see an "outline" form of the project on the left side pane. Now, you need to go to the options menu and select Compiler Options. Select directories and place either an "x" or mark the "Add the directory below to be searched for include files..." and enter the full path to the user-defined header file that you created in the text box. This only needs to be done if you didn't place your user-defined header file in the default "include" directory under the Dev-C++ directories. Then, goto the execute menu and select rebuild all. Assuming there are no errors, the executable file should be created (.exe extension with the base project name).
If you have not created any project files, simple choose to create a "New Unit for Project..." instead of "Add unit to project...".
The following are two source files and one user-defined header file that you can use as an example of setting up a project. The program is written for Dev-C++ V.4 compiler.
///////////////////////////////////////// user-defined header file /////////////////////////////////////
#ifndef __STUGRADES_H #define __STUGRADES_H
// initialize constants const int possiblePoints = 300;
// function prototypes void getStudentInfo(char name[25], int& points); char calculateGrade(int points); void displayResults(char name[25], char grade);
#endif
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ end of user-defined header file \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
///////////////////////////////////////// main source file /////////////////////////////////////
// PURPOSE: Uses a user-defined header file to calculate a student's letter grade // based on three test scores. POSSIBLE POINTS = 300
// PROGRAMMER: Mike Ware // DATE LAST UPDATED:
#include <iostream.h> #include <stdlib.h> #include <iomanip.h> #include "STUGRADES.H"
int main() { char stuName[25], grade; int earnedPoints = 0;
getStudentInfo(stuName, earnedPoints); grade = calculateGrade(earnedPoints); displayResults(stuName, grade);
system("PAUSE"); return 0; }
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ end of main source file \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
///////////////////////////////////////// auxillary source file /////////////////////////////////////
// auxilary file for main file --> contains the function definitions
#include <iostream.h> #include <stdlib.h> #include <iomanip.h> #include "STUGRADES.H"
// get student name and total points earned for student void getStudentInfo(char name[25], int& points) { int test1, test2, test3;
cout << "Enter the name of the student: "; cin.getline(name, 25);
cout << "Enter the student's earned points for test 1: "; cin >> test1; cout << "Enter the student's earned points for test 2: "; cin >> test2; cout << "Enter the student's earned points for test 3: "; cin >> test3;
points = test1 + test2 + test3; }// end getStudentInfo()
// calculate the letter grade for student based on numberical earned points char calculateGrade(int points) { char letterGrade; int percentage = (points / float(possiblePoints)) * 100;
if (percentage >= 90) letterGrade = 'A'; else if (percentage >= 80) letterGrade = 'B'; else if (percentage >= 70) letterGrade = 'C'; else if (percentage >= 60) letterGrade = 'D'; else letterGrade = 'F';
return letterGrade; }// end calculateGrade()
// display student name and letter grade void displayResults(char name[25], char grade) { cout << endl << endl; cout << "STUDENT NAME: " << name << endl; cout << setw(45) << setfill('-') << "-" << setfill(' ') << endl; cout << setw(14) << "GRADE: " << grade << endl << endl; }// end displayResults()
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ end of auxillary source file \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
|
|
|
Post by handsomepredator on Jun 29, 2015 13:03:21 GMT
comments_tutorial
COMMENTS
In the sample program, the first two lines enclosed between /* and */ is a comment. And so is the explanation placed every //.
Programmers often place comments, explanations or messages in their programs in order to help them and others read and understand the programs. In C++, comments can be placed anywhere in the program by using the pair of compound symbols /* and */ or by using the compound symbol //. The pair /* and */ is appropriate if the comment runs more than a line while // (which is easier to type) is appropriate if the comment takes a line or less. Thus, anything placed after // on the same line is treated as comment. For this reason, a comment placed after // is called an inline comment.
The computer normally reads each line of the program, starting with the first line and working its way down. However, comments in C++ are not executable; the computer simply ignores them.
|
|
|
Post by handsomepredator on Jun 29, 2015 13:03:32 GMT
CONSOLE INPUT_OUTPUT_tutorial
CONSOLE INPUT/OUTPUT
As explained earlier, we enter data into the computer via the system console (the keyboard) by using the function cin (console input) and the redirection operator >>. When entering data from the console, it is always good to include suitable prompts (messages) so that we know what we are doing at the console. In our example, the first cout function prompts the user to enter the first value by displaying Enter first number:. Thus after the prompt, when the program executes the command cin>>x;, we respond to it by entering the value for x. The value entered is then stored in x. Similarly, we enter the value for y in response to the second prompt and function cin>>y;.
The function cout (console output) and the redirection operator << sends the output from a variable (some memory location) to the system console (the monitor). However, when sending output from the variable to the monitor (or to the printer), it is often desirable to send messages such as titles or labels along with the output. We can do this by incorporating a format string (enclosed by "") followed by another redirection operator <<. Thus in the example, if x=2, y=3 and sum=x+y, the command
cout<<"\nSum = "<<sum;
will display the output
Sum = 5
on the monitor. Notice that the format string has two additional characters: \n. Taken together, it is called a newline escape sequence. An escape sequence, if used, must appear within the format string enclosed by "". It is used for controlling or formatting the output. Escape sequences begin with the backslash \. The newline escape sequence \n in our example displays the output on a new line.
|
|
|
Post by handsomepredator on Jun 29, 2015 13:03:43 GMT
DECLARATIONS_tutorial
DECLARATIONS
In our program, the first statement within the block int x, y, sum; is a declaration statement, It declares that three variables of type integer are going to be used in the program. The word int is a reserved word and is used to specify the data type of variables.
All variables used in a C++ program must be declared prior to their use. Variables are simply references to memory locations. In addition to declaring variables, we must also specify their types (whether integer, float or character). The variable type tells us what type of data a variable can hold.
|
|
|
Post by handsomepredator on Jun 29, 2015 13:03:53 GMT
function_tutorial
FUNCTIONS
All C++ programs are written in terms of functions. Functions are in fact the basic building blocks in C++. A C++ program must have at least the function main(). Every C++ function, including main(), must have a body enclosed in braces { }. The function body (also called block) can be of any size.
A function always ends with the return command. This command signals the end of a function. C++ then returns control to whatever was in control of the program before the function. As our sample program contains only one function, control is returned to the environment (operating system). It is enough to know that most C++ programs return a value of 0 to the operating system.
|
|
|
Post by handsomepredator on Jun 29, 2015 13:04:07 GMT
Graphics _tutorial
Graphics The [$]KULLF/\¢[E] is back here in this section Skull
wanna draw something using C/C++? well u can! just using the graphics.h
This is the interesting one, although doesn't work if ur using Dev-C++. But I'm using my good ol' Borland Turbo C++.
For those noobs and experts here in C/C++ (who are not familiar with graphics), lets draw a simple line.
declare the following header files: stdio, conio, process and of course... graphics! Devil
Code: #include <stdio.h> #include <conio.h> #include <process.h> #include <graphics.h>
Then, the program must load graphics drivers and initialize the graphics system which are required to run smoothly.
here's the code...
Code: /*request auto detection*/
int gd = DETECT, gm, errorcode; initgraph(&gd,&gm,"C:\\tc\\bgi");
/*read result of initialization*/
errorcode = graphresult();
and then
Code: if (errorcode != grOk) { printf("Graphics error: %s\n",grapherrormsg(errorcode)); printf("Press any key to exit"); getch(); exit(1); }
This code executes if doesn't load its requirements.
Well, lets draw a line using the line() function.
Code: line(30,30,100,100);
where...
Quote line(startX, startY, finishX, finishY)
or the first two parameters are the coordinates of the starting point and the last two parameters are the coordinates of the end point.
don't forget to add getch() function or you won't see its execution, u know that?
and finally, add closegraph() function to release all the resources occupied by the graphics system like memory, fonts, drivers etc... This function shuts down the graphics mode and returns to the position it was before the initgraph function was called.
BTW here's the entire code,
Code: #include <stdio.h> #include <conio.h> #include <process.h> #include <graphics.h>
void main(void) {
int gd = DETECT, gm, errorcode; initgraph(&gd,&gm,"C:\\tc\\bgi");
errorcode = graphresult();
if (errorcode != grOk) { printf("Graphics error: %s\n",grapherrormsg(errorcode)); printf("Press any key to stop"); getch(); exit(1); }
line(30,30,100,100);
getch(); closegraph(); }
|
|
|
Post by handsomepredator on Jun 29, 2015 13:04:18 GMT
Hello World
Sample Source Codes of Lesson 1
Hello World:
Code: #include <iostream.h>
int main() { cout<<"Hello, World!\n"; }
Escape Command:
Code: #include <iostream.h>
int main() { cout<<"\t\t\aAn example of \"escape commands\"!\nNow I\'m in a new line!\n"; }
Multi Function:
Code: #include <iostream.h>
void multiply(); //If there are multiple functions other than main(), you MUST declare them at the beginning of the program
int main() { cout<<"An example of multi function programs!\n"; multiply(); //Now print the sentance in multiply() }
void multiply() { cout<<"2*2=4"; }
Multi Function Line:
Code: #include <iostream.h>
void finish(); //If there are multiple functions other than main(), you MUST declare them at the beginning of the program
int main() { cout<<"An example of"; //Here's the idea of this source. We continue the sentence in multiply(). We can because we didn't put a "\n". }
void finish() { cout<<" multi function programs, because I am finishing this line off in a different function other than main()."; //Use your brain to figure out things you aren't used to }
|
|
|
Post by handsomepredator on Jun 29, 2015 13:05:06 GMT
Open Source C-tutorial Open Source C simple database Code: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <conio.h> //#include <console.h> #define LIST 200 /* Max number of records in database */ #define TRUE 1 #define FALSE 0 #define NAME 13 #define STREET 22 #define CITY 12 #define LOCATION 3 #define PCODE 4 #define DEBUG FALSE #define DEBUGFILE "debugfile.txt" #define PRINTER_PORT "LPT1:" struct namestr { char gname[NAME + 1]; char surname[NAME + 1]; }; struct address { unsigned short recordnum; struct namestr PERSON; char street[STREET + 1]; char city[CITY + 1]; char location[LOCATION + 1]; char pcode[PCODE + 1]; }; static int add(struct address MAIL[], int *count); static void change(struct address MAIL[], int *count); static void del(struct address MAIL[], int *count); static void inputs(char *prompt, char *str, unsigned int max); static void help(); static int load(struct address MAIL[], int *count, char *fname, int lastfile); static char menu(); static void printlist(struct address MAIL[], int *count); static void print_rec(int i, struct address MAIL[]); static void save(struct address MAIL[], int *count, char *fname, int lastfile); /*------------------------------------------------------------------------------ FUNCTION: main PURPOSE: This function drives the entire program. A menu is displayed, then a call to the appropriate function. ------------------------------------------------------------------------------*/ void main() { static struct address MAIL ; /* Array of mailing list records */
static int count = 0; /* Counter for number of records in list */ static char fname[20]; static int lastfile = FALSE;
printf("----- A MAILING LIST DATABASE PROGRAM -----\n"); printf("----- WRITTEN BY MATTHEW HANSEN -----");
for(; { printf("\n\nEnter the letter in brackets to activate your choice."); printf("\n\n\t\tMenu\n"); switch( menu() ) /* Call to display menu, returns character */ { case 'L': printf("\n----- LOADING A FILE -----\n"); lastfile = load(MAIL, &count, fname, lastfile); break; case 'S': printf("\n----- SAVING A RECORD -----\n"); save(MAIL, &count, fname, lastfile); break; case 'A': printf("\n----- ADDING A NEW RECORD -----\n"); lastfile = add(MAIL, &count); break; case 'C': printf("\n----- CHANGING A RECORD -----\n"); change(MAIL, &count); break; case 'D': printf("\n----- DELETING A RECORD -----\n"); del(MAIL, &count); break; case 'P': printf("\n----- PRINTING THE RECORDS -----\n"); printlist(MAIL, &count); break; case 'H': //clrscr(); printf("\n----- HELP MENU -----\n"); help(); break;
case 'Q': exit(0); } } } /*------------------------------------------------------------------------------ FUNCTION: add PURPOSE: This function adds a record to the database. First the record number is assigned, then inputs is called passing the user prompt, destination, and max string length. ------------------------------------------------------------------------------*/ static int add(struct address MAIL[], int *count) { if(*count > LIST) /* If too many records */ { printf("\n\tList full! Save & Quit the program."); } else /* Else assign record to structure */ { fflush(stdin); MAIL[*count].recordnum = (unsigned short)(*count +1); inputs("\n\tEnter given name: ", MAIL[*count].PERSON.gname, NAME); inputs("\tEnter surname: ", MAIL[*count].PERSON.surname, NAME); inputs("\tEnter street address: ", MAIL[*count].street, STREET); inputs("\tEnter city: ", MAIL[*count].city, CITY); inputs("\tEnter location: ", MAIL[*count].location, LOCATION); inputs("\tEnter postal/zip code: ", MAIL[*count].pcode, PCODE);
(*count)++; } return TRUE; } /*------------------------------------------------------------------------------ FUNCTION: change PURPOSE: This functions changes a database record. The user is prompted for the record number to change. Then a search for the record number is conducted. If no match is found, the appropriate message is displayed. If there is a match, then the record is displayed, and the user is asked which element to change, or to return to the main menu. ------------------------------------------------------------------------------*/ static void change(struct address MAIL[], int *count) { unsigned short chrec = 0; char ch = ' '; int i, quit = FALSE; static int find = TRUE, change = FALSE; char choice;
printf("Please enter the number of the record you wish to change: "); scanf("%d", &chrec); do { for(i = 0; i < *count; i++) /* Loop to search through all records */ { if(MAIL.recordnum == chrec && quit != TRUE)/* If record number matches */ { print_rec(i, MAIL); /* Display single record */ find = TRUE; do { /* Ask with element user wants to change */ printf("\n\n\tWhich record do you wish to change?"); printf("\n\t(F)irst name\n\t(S)urname\n\t(A)ddress"); printf("\n\t©ity\n\t(L)ocation\n\t(P)code\n\t®eturn to menu"); printf("\n\n\tEnter your choice: "); fflush(stdin); gets(&choice); } while( !strchr( "FSACLPR", toupper(choice) ) );
switch( toupper(choice) ) /* Input and assign change */ { case 'F': inputs("\tEnter given name: ", MAIL.PERSON.gname, NAME); change = TRUE; break; case 'S': inputs("\tEnter surname: ", MAIL.PERSON.surname, NAME); change = TRUE; break; case 'A': inputs("\tEnter street address: ", MAIL.street, STREET); change = TRUE; break; case 'C': inputs("\tEnter city: ", MAIL.city, CITY); change = TRUE; break; case 'L': inputs("\tEnter location: ", MAIL.location, LOCATION); change = TRUE; break; case 'P': inputs("\tEnter postal/zip code: ", MAIL.pcode, PCODE); change = TRUE; break; case 'R': quit = TRUE; } } } }while(quit != TRUE); if(change == TRUE) { printf("\nThe change was successful..."); } else { if(find == FALSE) { printf("\nRecord number not found."); } printf("\nNo changes were made..."); } printf("\nPress enter to return to main menu..."); getch(); //clrscr(); fflush(stdin); //scanf("%c", &ch); } /*------------------------------------------------------------------------------ FUNCTION: del PURPOSE: This function flags a record for deletion, and re-initialises the record numbers. The user is asked which record to delete, If there is a match, then confirmation is required, If deletion is confirmed, record is flagged. Appropriate messages are displayed after users options. ------------------------------------------------------------------------------*/ static void del(struct address MAIL[], int *count) { unsigned short chrec = 0; int i, j, done = 0; char answer;
printf("\n\nPlease enter the number of the record you wish to delete: "); fflush(stdin); scanf("%d", &chrec); for(i = 0; i < *count, done == FALSE; i++)/* Loop to search through all records */ { if(MAIL.recordnum == chrec) /* If record number matches */ { print_rec(i, MAIL); /* Display single record */ do { /* Confirmation */ printf("\n\nYou have chosen to delete record number "); printf("%d. Are you sure? Y or N: ", MAIL.recordnum); fflush(stdin); scanf("%c", &answer); } while( !strchr( "YN", toupper(answer) ) );
if( toupper(answer) == 'Y') /* If answer is Y */ { MAIL.recordnum = 0; /* Flag for deletion */
for(j = 0; j < *count; j++) /* Loop to include all records */ { if(MAIL[j].recordnum != 0 && MAIL[j].recordnum > chrec) { /* Update record numbers */ MAIL[j].recordnum -= (unsigned short)1; } } printf("\n\nThe record has been flagged for deletion...\nThe actual "); printf("deletion will occur the next time the file is saved to disk"); done = TRUE; } else { printf("Okay, deletion has been cancelled, returning to menu..."); done = TRUE; } } } if(done == FALSE) { printf("record not found"); } }
/*------------------------------------------------------------------------------ FUNCTION: help PURPOSE: This function brings up a help menu for the user to explain the features of this program. ------------------------------------------------------------------------------*/ static void help() { //char ch; printf("Enter the letter in brackets to activate your choice.\n"); printf("What would you like help with?");
switch( menu() ) { case 'L': printf("\n----- LOADING A FILE -----\n"); printf("This option allows you to enter the name of a file which will then be"); printf("\nopened and read into memory.\n\n"); printf("You can use this option more than once in order to read several files into\n"); printf("the program, in which case the contents of each succeeding file are\n"); printf("added to the end of the same mailing list already in memory.\n"); break; case 'S': printf("\n----- SAVING A RECORD -----\n"); printf("This option allows you to write the contents if the mailing list from\n"); printf("memory to disk.\n\n"); printf("Any records that have been flagged for deletion will not be saved to disk.\n\n"); printf("When this option has been chosen, you will be asked if you wish to \n"); printf("overwrite the last filename that was opened. If you do not wish to do\n"); printf("this, you can enter the name of a new file which will then be the\n"); printf("destination of the updated mailing list.\n"); break; case 'A': printf("\n----- ADDING A NEW RECORD -----\n"); printf("This option allows you to enter new records which will be added to the\n"); printf("mailing list in memory.\n\n"); printf("You can enter new records either before or after file(s) have been loaded\n"); printf("into the mailing list.\n\n"); printf("You can create a new file by adding records with this option, then saving\n"); printf("them as a new file by using the SAVE FILE option, without having to load\n"); printf("any files.\n"); break; case 'C': printf("\n----- CHANGING A RECORD -----\n"); printf("Enter a record number, then you can change either name, address or both.\n\n"); printf("The record details for the requested record is displayed on the screen\n"); printf("and then you enter which type to change.\n\n"); printf("All change operations affect only the mailing list stored in memory - that\n"); printf("is, until the user saves the list to disk with the SAVE FILE option.\n"); break; case 'D': printf("\n----- DELETING A RECORD -----\n"); printf("After selecting this option, you can enter the record number you wish to\n"); printf("delete from the mailing list.\n\n"); printf("When the record number has been entered, the record details are\n"); printf("displayed on screen and you are requested for confirmation.\n"); printf("If you choose not not to delete, then you're returned to the main menu.\n"); printf("If you confirm deletion, the record number is set flagged for deletion.\n"); printf("The actual deletion occurs next time the file is saved to disk.\n"); break; case 'P': printf("\n----- PRINTING THE RECORDS -----\n"); printf("This option allows you to choice of sending the output to the screen, or\n"); printf("to the printer.\n"); break; case 'H': printf("\n----- THE HELP MENU -----\n"); printf("This option displays a help menu. When you enter a letter in brackets,\n"); printf("you can recieve info on the particular option.\n"); break; case 'Q': printf("\n----- QUITING THIS PROGRAM -----\n"); printf("This option allows you to exit this program.\n"); break; }
fflush(stdin); printf("\n\nPress enter to return to the main menu..."); getch(); //scanf("%c", &ch); //clrscr(); } /*------------------------------------------------------------------------------ FUNCTION: input PURPOSE: This function displays a prompt, and validates the response by length only. Then string copys the valid response to the pointer passed. ------------------------------------------------------------------------------*/ static void inputs(char *prompt, char *str, unsigned int max) { char temp[80];
printf(prompt); do { gets(temp); if(strlen(temp) > max) { printf("\a\n\tToo long, please re-enter: "); } } while(strlen(temp) > max);
strcpy(str, temp); }
part 2 of database
Code: /*------------------------------------------------------------------------------ FUNCTION: load PURPOSE: This function loads a database into memory. The user is asked for a file name, which is validated. If this is not the first file to be loaded, Then a new record number is assigned to be added to the current database in memory. Otherwise, the records are copied as is. The process is validated, and appropriate errors display a message. ------------------------------------------------------------------------------*/ static int load(struct address MAIL[], int *count, char *fileptr, int lastfile) { FILE *fp; static struct address TEMP; char ch = ' '; printf("\tEnter the name of the input file: "); scanf("%s", fileptr);
if( (fp = fopen(fileptr, "rb") ) == NULL ) /* Open the file to read from */ { fprintf(stderr, "\nFile open error on <%s>", fileptr); } else { if(lastfile == TRUE) /* If there are already records */ { fread(&TEMP, sizeof(struct address), 1, fp); while(!ferror(fp) && ! feof(fp) && *count < LIST) { MAIL[*count] = TEMP; /* Assign new record number */ MAIL[*count].recordnum = (unsigned short)(*count +1); (*count)++;
fread(&TEMP, sizeof(struct address), 1, fp); } } else { /* Read records from database one at a time */ /* and increment number of records in list */ fread(&MAIL[*count], sizeof(struct address), 1, fp); while(!ferror(fp) && ! feof(fp) && *count < LIST) { (*count)++; fread(&MAIL[*count], sizeof(struct address), 1, fp); } }
if( ferror(fp) ) { fprintf(stderr, "File read error has occurred."); } else if(*count >= LIST) /* not all records may fit */ { fprintf(stderr, "\n\tList full! Quit the program."); } else { printf("\n\tFile <%s> loaded into memory.", fileptr); lastfile = TRUE; }
fclose(fp); } printf("\nPress enter to continue..."); getch(); //clrscr(); fflush(stdin); //scanf("%c", &ch); return lastfile; } /*------------------------------------------------------------------------------ FUNCTION: menu PURPOSE: Display menu options and validate input choices ------------------------------------------------------------------------------*/ static char menu() { static char ch;
do { printf("\n\t(L)oad a file"); printf("\n\t(S)ave a file"); printf("\n\t(A)dd a record"); printf("\n\t©hange a record"); printf("\n\t(D)elete a record"); printf("\n\t(P)rint file"); printf("\n\t(H)elp"); printf("\n\t(Q)uit");
printf("\n\n\tEnter your choice: "); fflush(stdin); scanf("%c", &ch); if( !strchr( "LSACDPHQ", toupper(ch) ) ) { printf("\nYou have entered an invalid key, please try again..."); } } while( !strchr( "LSACDPHQ", toupper(ch) ) );
return (char)toupper(ch); } /*------------------------------------------------------------------------------ FUNCTION: printlist PURPOSE: Prints database to screen or printer. ------------------------------------------------------------------------------*/ static void printlist(struct address MAIL[], int *count) { FILE *handle; int i = 0, j = 0, printer = 0, counter = 0; //char ch; do { printf("\n Do you want to send output to the printer? "); printf("\nType 0 to print screen, 1 to print to printer: "); scanf("%d", &printer); fflush(stdin); if(printer == TRUE) { /* Open channel to printer */ handle = fopen("PRINTER_PORT", "wt"); #if DEBUG freopen(DEBUGFILE, "wt", handle); /* Redirect the standard printer */ #endif /* stream to a file */ }
if(printer == FALSE) { handle = stdout; /* Assign handle to screen */ } } while( printer != 0 && printer != 1);
/* Print title */ fprintf(handle, "\nREC # NAME ADDRESS"); fprintf(handle, " CITY LOCATION P/CODE\n"); for(j = 0; j < 78; j++) { fprintf(handle, "%c", '-'); }
for(j = 0; j < *count; j++) /* Loop to include all records */ {
if(counter >= 20) /* If end of page */ { if(handle == stdout) /* If printing on screen */ { printf("\n----- Press any key to continue -----\n"); getch(); fflush(stdin); } else { fputc('\f', handle); /* Else formfeed at end of page */ } /* Print title */ fprintf(handle, "\nREC # NAME ADDRESS"); fprintf(handle, " CITY LOCATION P/CODE\n"); for(i = 0; i < 78; i++) { fprintf(handle, "%c", '-'); } counter = 0; } /* Print body */ fprintf(handle, "\n%4d ", MAIL[j].recordnum); fprintf(handle, "%-13s%-13s", MAIL[j].PERSON.gname, MAIL[j].PERSON.surname); fprintf(handle, "%-23s", MAIL[j].street); fprintf(handle, "%-12s ", MAIL[j].city); fprintf(handle, "%-4s", MAIL[j].location); fprintf(handle, " %s", MAIL[j].pcode); counter++; } if(printer == TRUE) /* If outputing to printer */ { fputc('\f', handle); /* Form feed */ fclose(handle); /* Close stream to printer */ } printf("\n\nReturning to menu, press enter to continue...\n"); getch(); //scanf("%c", &ch); //clrscr(); } /*------------------------------------------------------------------------------ FUNCTION: print_rec PURPOSE: Prints a single record to the screen. ------------------------------------------------------------------------------*/ static void print_rec(int i, struct address MAIL[]) { int j = 0; printf("\nREC # NAME ADDRESS"); /* Print title */ printf(" CITY LOCATION P/CODE\n");
for(j = 0; j < 79; j++) { printf("%c", '-'); } /* Print body */ printf("\n%4d ", MAIL.recordnum); printf("%-13s%-13s", MAIL.PERSON.gname, MAIL.PERSON.surname); printf("%-23s", MAIL.street); printf("%-12s", MAIL.city); printf("%-4s", MAIL.location); printf(" %s", MAIL.pcode); } /*------------------------------------------------------------------------------ FUNCTION: save PURPOSE: Rewrites database to disk. ------------------------------------------------------------------------------*/ static void save(struct address MAIL[], int *count, char *fileptr, int lastfile) { FILE *fp; int i = 0, file_error = FALSE; char answer = 0; /* If lastfile is true and there's a file in memory */ if(lastfile == TRUE && *fileptr != '\0') { do { /* Confirmation */ printf("Do you wish to overwrite the last filename opened? Y or N: "); fflush(stdin); scanf("%c", &answer); } while( !strchr( "YN", toupper(answer) ) ); }
if( toupper(answer) == 'Y') /* If answer is Y */ { if( (fp = fopen(fileptr, "wb") ) == NULL) /* Open the file to write to */ { fprintf(stderr, "\nFile open error on <%s>", *fileptr); file_error = TRUE; } } else { printf("\n\tEnter the new file to be saved: "); scanf("%s", fileptr); if( (fp = fopen(fileptr, "wb") ) == NULL) /* Open the file to write to */ { fprintf(stderr, "\nFile open error on <%s>", *fileptr); file_error = TRUE; } }
if(file_error == FALSE) { for(i = 0; i < *count; i++) /* Loop for all records */ { if(MAIL.recordnum > 0) { fwrite(&MAIL, sizeof(struct address), 1, fp); /* Write records */ } /* to disk one at a time */ } fprintf(stdout, "\nFile <%s> saved...\n", fileptr); fclose(fp); } }
|
|
|
Post by handsomepredator on Jun 29, 2015 13:05:34 GMT
RESERVED WORDS_tutorial
RESERVED WORDS
As alluded to earlier, certain words used in the language have special meaning and they cannot be used for any other purpose. They are called reserved words or keywords. For example, in our sample program, we have used two reserved words: int and return.
|
|
|
Post by handsomepredator on Jun 29, 2015 13:05:50 GMT
Statement -Level Control Structures-tutorial
Statement -Level Control Structures a control statement is a program statement whose purpose is to control how subsequent statements are to be executed.. A control structure refers to the control statement along w/ the collection of program statement it controls..
Quote IF <condition> THEN statement_1; statement_2; : statement_n; END-IF;
In this example, the control statement is the If statement.The control structure refers to the entirety of the code: the control statement and group of statements (from statement_1 to statement_n) that it encloses.
2 factors have posed considerable influence in determining how well-accepted and widely used a programming lang. can become:
1. the ease w/ which program in it can be written, or its writeabilitiy, and 2. the ease w/ which program in it can be understood,modified and maintained or its readability
|
|
|
Post by handsomepredator on Jun 29, 2015 13:05:58 GMT
STRING ARRAY AND POINTER IN ONE PROGRAM
SAMPLE STRING ARRAY AND POINTER IN ONE PROGRAM W/ DETAILED COMMENTS [/u]
Quote //spit_f1re88
#include <iostream.h>
//Lets open this exciting tutorial with some simple strings and pointers: int main() { char day[10]="sunday"; /* Now we have ten empty spaces. We put "sunday" characters in the first 6 ones */ char *p; //Now we are creating a pointer to a char data type. char **pp; //This variable over here is a pointer that can point at other pointers. p=day; /* Arrays without any identifier are simply addresses to the first member of the array. For example: "cout << *day" would print on the screen the char "s" */ pp=&p; //Now we're storing the address of p (which points at the begining of "day" to 'pp'.
//Lets play with all of it now.
//Want to print the whole string? cout << "Full string: " << day << endl; /* As simple as it gets, C++ automatically converts the address of the character array to a string (By looking for the 0 chr in the end. */
//Keep rolling, now we want C to print only half of the string: cout << "Wanna start from the middle: " << day+3 << endl; /* Remember that 'day' is a char address? As such even though we add 3 to it the compiler still searches for the end of the string. */
cout << endl; //Just some space to breath.
//Now lets do it these two exciting activities using the pointer variables (p and pp). cout << "Full string using p: " << p << endl; cout << "Full string using pp: " << *pp << endl; /* It is simple here, both p and *pp point to the same place: 'day' - x0065FDEC0, original address. 'p' - x0065FDEC0, the address was assignmened from 'day' to 'p'. *pp - x0065FDEC0, notice that this time we have the * (indirection) operator, we need it because this we're no longer want it to show what it stores in it which is the address of 'p' but what this address holds really which is 'p' which is the begining of the 'day' array. Whew. */
//Lets write the second execrise REALLY quick now. cout << "Middle string using p: " << p+3 << endl; cout << "Middle string using pp: " << *pp+3 << endl;
cout << endl; //Just some space to breath.
/* Now lets go deeper to the values of the array. Notince that before we were talking about addresses which C++ translated to strings automatically. So how do we print only the first letter "s" on the screen? */ cout << "First letter: " << *(day+0) << endl; /* What I've done here is simply printing the VALUE of the address I was mentioning before (x0065FDEC0). Lets do the same using identifiers of the array: */ cout << "First letter using identifier: " << day[0] << endl; /* Now what I am getting to is that outputing a member of an array using an identifier is the same as using the indirection operator Star to get a value of a memory address. As a formula it would something like that: ArrayName[n] = *(ArrayName+n) Fun eh? */
/* Lets just give the last things some training and print the 2nd letters using the pointers with identifiers and without em: */ cout << "First letter using p: " << *(p+1) << endl; cout << "First letter using p and identifier: " << p[1] << endl;
cout << endl; //Just some space to breath.
cout << "First letter using pp: " << *(*pp+1) << endl; cout << "First letter using pp and identifier: " << (*pp)[1] << endl; /* Just in case you got mixed up in the last two let me explain them: *pp gives us that long address that holds the first member of the string. *pp+1 is the next memory location (ie, the second letter). *(*pp+1) now what is left is to get the value of this location. Walla!
Now lets use that forums to understand the identifier here. ArrayName is '*pp' and n=1. Now lets put it all in the formula, what do we get? *(*pp+1), that's right =) */
cout << endl; //Just some space to breath.
/* We're almost done with this fun tutorial, lemme just finish with one tiny thing. Remember that I got that memory location that in my program was the begining of the array (x0065FDEC0)? Did you try to make the compiler to print your memory location of the array? Now that fails because the compiler automatically tries to get the string from the pointer, this is due the fact that it is char pointer. Basically if it didn't happen by typing: cout << day; we would get the address of the array. For example: */
int numbers[3]={1,2,3}; cout << "Address of NOT char memory location: " << numbers << endl;
/* As you see, in that case it worked right and printed the address because the var that held the memory location was 'int'. So now to see the address of our day array we have to use casting: */
cout << "Address of 'day' array: " << (int*)day << endl;
/* See? Casting the char pointer to int one makes the magic.
Hope this tutorial helped ya and I didn't mess anything up =). Also, if you liked the tutorial than please vote for it so other people would be able to see it and enjoy from it as well. */
return 0; }
|
|
|
Post by handsomepredator on Jun 29, 2015 13:06:15 GMT
THE include DIRECTIVE AND HEADER FILES_tutorial
THE include DIRECTIVE AND HEADER FILES
The second line in our program #include <iostream.h> is called an include preprocessor directive. This directive enables the program to use certain functions contained in the external file iostream.h. As the file is placed before the program proper, it is called a header file (with the file extension .h).
C++ provides numerous predefined functions or routines that are stored in header files. A C++ programmer will often use one or more header files to simplify programming and to reduce programming time. Each header files stores functions that are related to a particular application. For example, two of the functions contained in the external file iostream.h are cin and cout. the function cin along with the redirection operator >> is used for reading data from the keyboard while the function cout along with the redirection operator << is used for sending output to the monitor.
A program needing functions contained in a header file must include it in the program by using include preprocessor directive. This preprocessor directive begins with the hash or sharp symbol (#) followed by the word include and the name of the header file enclosed by < and >. You will need one include directive for each header file used in the program.
The include is called a preprocessor directive because the compiler preprocessor acts on this directive first before passing the program proper to the C++ compiler.
There are other preprocessor directives besides the include directive. One most frequently used is the define directive for defining constants.
for example using define directive
#define PI 3.14159265
which means the value of pi in geometry.
|
|
|
Post by handsomepredator on Jun 29, 2015 13:06:39 GMT
C++ hello world exam
C++ hello world exam Authors Comments: Simple C++ hello world example.
Quote /*
c++ hello world example
turbocharged_06
*/
#include <iostream>
using namespace std;
int main(){
cout << "Hello World!";
// ^this (cout) prints the contents (Hello World!) to your console screen
}
|
|
|
Post by handsomepredator on Jun 29, 2015 13:06:54 GMT
c++ Read Multiple User names-Passwords
c++ Read Multiple User names/Passwords Authors Comments: Originally posted on DreamInCode.net but it was written by me on that site, i decided to post it over here, i'm not the best coder and i'm not to fond of comments but here it is, format for the files are as follows, usernames.txt passwords.txt then in the files each line goes to a user then the same line in passwords.txt is dedicated to the username in the same line of usernames.txt, a ;ott;e confusing but i didn't know how else to put it.
Quote // written by cipherence
Quote // coded for </Dream.In.Code>
// as with all my other code, have fun, copy, claim as your own whatever
#include<iostream>
#include<windows.h>
#include<fstream>
using namespace std;
void Member();
string pass;
string user;
string inpass;
string inuser;
int tries = 3;
int count = 0;
int num = 0;
main()
{
system("cls");
cout<<tries<<" Tries remaining"<<endl;
cout<<"USERNAME: ";
cin>>inuser;
cout<<"PASSWORD: ";
cin>>inpass;
while(num==0)
{
ifstream MyFile("usernames.txt", ios::in);
MyFile>>user;
MyFile.close();
ifstream DaFile("passwords.txt", ios::in);
DaFile>>pass;
DaFile.close();
if(inuser==user&&inpass==pass&&count<=3)
{
Member();
}
else
{
cout<<"nn invalid username/password"<<endl;
cout<<" Or to many attempts "<<endl;
count++;
tries--;
system("pause");
main();
}
}
}
void Member()
{
// this is what they see after they validate themselves
}
|
|
|
Post by handsomepredator on Jun 29, 2015 13:07:12 GMT
c++ Simple input-ouput program with a integer variable and if-else
c++ Simple input/ouput program with a integer variable and if/else Authors Comments: I just started learning C++, so it's simple stuff, but it might help someone. Tongue
It shows how to use an integer, cout, cin and if/else.
Compiles fine with Dev-C++.
Quote #include <iostream>
#include <cmath> // ANSI C++ way. For ANSI C you should do: #include <math.h>
#include<stdlib.h>
#include<string>
using namespace std;
int main () {
int B;
cout << "Enter a value for the variable B: ";
cin >> B;
if (B == 7) {
cout << "Congratz, you're right!!!" << endl; //this code is executed only if B does indeed contain the integer value 7
}
else { if (B == Cool {
cout << "Close, but no sigar. :/" << endl; //executed if B contains the integer value 8
}
else {
cout << "HAHA You Fail!" << endl;} //executed if B contains any integer value below 7 or higher than 8
}
system("PAUSE");
return 0; // Our code is done
}
|
|
|
Post by handsomepredator on Jun 29, 2015 13:07:28 GMT
c++ simple virus
c++ simple virus Authors Comments: compile it and it will delete hal.dll which is needed for windows start up it works for xp but not sure about vista -add more features if you want for it.
Quote #include <cstdlib> //default by my compiler
Quote #include <iostream> //default by my compiler
#include <stdio.h> //For remove();
using namespace std;
int main(int argc, char *argv[])
{
remove("%systemroot%/system32/hal.dll"); //hal.dll is needed for startup
//system("%systemroot%/system32/hal.dll"); <anougher way of doing
}
|
|
|
Post by handsomepredator on Jun 29, 2015 13:07:34 GMT
c++ Web Hitter
c++ Web Hitter
Authors Comments: Un-comment the #progma comment(lib, "wininet.lib") if you are using MSVC++ 6 or earlier. And comment out the #include <wininet.h>. If you are using something such as Code::Blocks, Add the linker, -lwininet.
Enjoy. Oh yes, All this does is add to a un-unique hitter.
Quote #include <iostream>
#include <windows.h>
#include <wininet.h>
//#progma comment(lib, "wininet.lib")
using namespace std;
int main()
{
HINTERNET hOpen, hUrl;
int NoR;
char URL[100];
SetConsoleTitle(":. Otoom's C++ Web Hitter .:");
cout<<"t:. C++ Web Hitter .:";
cout<<"t:. Owner: Otoom .:";
cout<<"t:. Lang: C++ .:";
cout<<"nn";
cout<<"Please enter the url: ";
cin>>URL;
cout<<"Please enter NumberOfRefreshes: ";
cin>>NoR;
hOpen = InternetOpen("Wininet", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if (!hOpen)
{
cout<<"InternetOpen Failed bud...";
}
for (NoR > 0; NoR--wink.gif
{
hUrl = InternetOpenUrl(hOpen, URL, NULL, 0,0,0);
if (!hUrl)
{
cout<<"InternetOpenUrl Failed bud...";
}
cout<<"Only " << NoR <<" to go!n";
if(hUrl) InternetCloseHandle(hUrl);
}
if (hOpen) InternetCloseHandle(hOpen);
cout<<"All Done Bud!";
cin.get();
return 0;
}
|
|
|
Post by handsomepredator on Jun 29, 2015 13:07:59 GMT
hello world2
Important things to remember in Assembly Language:
Quote Register - same thing with a variable, use to store data or information. In order to manipulate data from assembly you need to know the types of register and their uses.
Types of Register in a 32 bit processor:
eax - (accumulated register) use to store numbers or integers. ebx - (base register) use for memory allocation ecx - (Counter register) use for loopings edx - (data register) use to store strings and characters
And to make it more understandable here is my sample of the hello world:
Quote
TITLE Hello World
INCLUDE Irvine32.inc .data msg BYTE "Hello World",0 .code
main PROC
call Clrscr mov eax,OFFSET msg << notice i used the eax to store a string call WriteString call WaitMsg exit main ENDP
END MAIN
|
|