Você está na página 1de 7

C++ is an object orientated programming language in other words it can have several parts known as classes or object which

can be called by a driver program, the main function. This means that we can also include other files and use functions from them, however as this is only a basic guide to start you programming we only look at this from the perspective of including some basic libraries that come with most compilers. The first thing you need to know is the basic code you need to start programming First off we need to include the iostream file to do this, at the top of our document we type:

#include <iostream> using namespace std;


This allows us to use classes from the iostream library, these are used for the basic input and output commands, also we must have a main() function, at least if we want to run the program (its not needed if your creating class to be used by others, however this is outside the scope of this tutorial.) inside the "main()" we write our code as you can see below: Note: comments can be added using "//" for one line comments or /* comment */for more then one line as seen below

/* this is a program to demonstrate the basics of a c++ programme, it includes comments, header files, the main() function and cout*/ #include <iostream> using namespace std; //includes the header file iostream //tells the compiler to use the std library

int main() // declares the function main which returns an int { //tells the program to take everything between here and the close as main cout<<"Hello World!\n"; // displays Hello world on the console

cin.get(); return 0; }

// stalls the program until a key is pressed // returns 0 (a 1 would indicate an error // closes main

Let's look at the elements of the program in more detail. The #include is a "pre-processor" that tells the compiler to put code from the header called iostream into our program. By including header files, you can gain access to many different functions. the cout function requires iostream. Following the include is the statement, "using namespace std;". This line tells the compiler to use a group of functions that are part of the standard library (std). By including this line at the top of a file, you allow the program to use functions such as cout. The semicolon tells the compiler that this is a line that should be executed. You will see later on that the semicolon is used to end most but not all commands in C++. The "cout" function tells the compiler to display the contents on the screen. cin.get() is used to hold the program from completing until a key is pressed, and finally the "return 0;" is used to return the exit code 0(no errors) The cout function can be manipulated in many ways, it can display hard coded text but also it can display variables, each type must be separated using lt;< for example:

cout<<"the number is "<<var1<<endl;


The above will print out "the number is " the value contained in var1 and move to the next line. The command cin.get() is another function call: it reads in input and expects the user to hit the return key. this command keeps the program from closing until the user enters a key it expects you to hit enter. At the end of main, the closing bracket, our program will return the value of 0 (and integer, hence why we told main to return an int) to the operating system. This return value is important as it can be used to tell the OS whether our program succeeded or not. You can cut and paste the code above into a file, save it as a .cpp file( tells the OS its c++ source code). In Dev C++ you can compile and run the code by clicking the colourful button in the top left hand corner of the window. You might start playing around with the cout function and get used to writing C++. Comments are critical for all but the most trivial programs and this tutorial will often use them to explain sections of code. When you tell the compiler a section of text is a comment, it will ignore it when running the code, allowing you to use any text you want to describe the real code. When you are learning to program, it is useful to be able to comment out sections of code in order to see how the output is affected.

Variables
A very important part of this tutorial is the use of variables, C++ allows for many types of variables these include integers (int) number values, floating points (float) numbers with decimal points, characters (char) ASCII characters, strings (string) strings of characters. The advantage of variables is that there value can change at any point, all variables must be declared, they are given symbolic names instead of values and when called read the data stored at the variables address.

/*to demonstrate variables */ #include <iostream> using namespace std; int main() { int number; float decimal; char character; string word; number = 1; decimal =1.1; character = 'f'; word = "hello"; cout<<number<<" "<<decimal<<" "<<character<<" "<<word<<endl; cin.get(); return 0; }
Copy this code compile it and check out the result, have a try at switching it around a bit see what you can do, variables can be used to store calculations as well. for example you switch the line "number = 1;" to "number = 12 + 14;" and run it again, this gives number the value 26, there are several other operators, "+" means addition, "-" means subtract, "/" means divide, "*" means multiply, % means modulus, in case you don't know modulus gives you the remainder of a division, play around try out the different operators. You can also add, subtract, multiply and divide variables like var1 =var2 + var3, however you do have to assign a value to var2 and var3 before hand.

//includes the header file iostream //tells the compiler to use the std library

User input
The cin function reads in values in much the same format that cout outputs values, there are however some flaws that must be addressed, if you try to read in multiple values after entering the first value the program reads the value into the variable how ever the next cin might take the return pressed on the first time, this is solved using cin.ignore() which is a dummy that is used to take the return without assigning it to a variable, a simple input should look like this:

/* to demonstrate cin function*/ #include <iostream> using namespace std; //includes the header file iostream //tells the compiler to use the std library

int main() { int var1; char var2; cin>>var1; //reads in a value from the keyboard cin.ignore(); //reads a dummy cin>>var2;//reads in a value from he keyboard cin.ignore(); //reads a dummy cout<<var1<<var2<<endl;//prints values entered cin.get(); return 0; }//end main
cin can be used to scan in strings as well in the same way.

/* to demonstrate cin function with strings*/

#include <iostream>

//includes the header file iostream

using namespace std;

//tells the compiler to use the std library

int main() { string var1; cin>>var1; //reads in a value from the keyboard cin.ignore(); //reads a dummy cout<<var1<<endl;//prints values entered cin.get(); return 0; }//end main
Now we have come to the end of this tutorial you should be able to make some simple programs in the next tutorial I will cover if, while, do while and for statements, I will also cover the basics of arrays.

PEARL
Perl is an interpreted language that is very popular in the Unix community because it has a rich and powerful feature set, but is still easy to use. Perl borrows heavily from other languages such as C and awk and is especially useful for processing text, generating reports, and handling Common Gateway Interface (CGI) requests submitted via Web browsers. Perl has been ported to many non-Unix environments, including DOS, OS/2, Macintosh, VMS, and Windows NT. The fact that a Perl program can run with little or no modification on many different platforms is another reason for its popularity. In this section, I'll introduce you to basics of Perl and point you to some resources where you can learn more. Perl Basics To create a Perl script, use a text editor to enter Perl commands, save the file with a.plextension (such assample.pl),and then usechmodto mark the file as executable. The extension is not required, but it's a common Unix convention and will help you identify your Perl source files without looking inside. Here's a very simple Perl script: #!/usr/bin/perl print "I am here. \n"; The mysterious first line starting with "pound splat slash" is required for all Perl scripts to run; it tells the system where to find the Perl interpreter. Hopefully, you've already figured out that this program prints a message followed by the newline character.

Unlike theechocommand in Bash scripts, Perl'sprintcommand doesn't automatically send a carriage return and line feed. If you forget the\nsequence, the nextprintcommand will start on the same line. Also note that all Perl statements must end with a semicolon. A variable in a Perl script is a means of referencing a numeric or character value. As in Bash scripts, Perl doesn't require you to declare a type for your variables. Perl figures out by context whether the value should be treated as a number or a character string and will even perform character-to-numeric value conversions when necessary. To assign or access the value (contents) of a variable, prefix it with a dollar sign. Spaces before or after the equal sign are optional, but if you want to assign a variable that contains character data, you must put quotation marks around the string. $num=5; $stuff = "chocolate truffles"; $user = $ENV{USER}; In these examples, Perl assigns 5 to the numeric variable$num, "chocolate truffles" to the variable$stuff, and the value of the USER environment variable to$user. This is a good time to note that there are several distinct ways to use quotation marks in a Perl script. Let's look at the differences among single quotation marks, double quotation marks, backticks, and the backslash character and then follow up with some examples. Single quotation marks, as in the preceding example, will always get you exactly what's inside the quotation marks--any characters that might otherwise have special meaning (like the dollar sign or the backslash) are treated literally. Usedouble quotation markswhen you want to assign a string that contains special characters that need to be interpreted. Thebackslashis used toescape(treat literally) a single character (such as $ or *) that might otherwise be treated as a special character. Usebackticksto indicate that the string is a Linux command that should be executed, with the results assigned to a variable.
Now let's look at some examples that show when to use each method of quoting:

$user = $ENV{USER}; print 'Good Morning $user'; Yields: Good Morning $user $user = $ENV{USER}; print "Good Morning $user"; Yields: Good Morning hermie In the first case, the results would probably not be what you wanted. The single quotation marks caused Perl to not treat$useras a variable. In the second case, the results look much better. The double quotation marks allowed Perl to substitute the value of$userin the string. Here's another example that demonstrates a common error: $costmsg = "Price is $5.00"; print "$costmsg"; Yields:Price is .00 We thought enough to quote the string, but the dollar sign tells Perl to use the value in the$5variable, which is as yet undefined. We can easily solve the problem by prefixing the dollar sign with a backslash, as shown here: $costmsg = "Price is \$5.00"; print "$costmsg"; Actual result: Price is $5.00 Finally, here's an example using backticks to execute a Linux command and capture the results in a Perl variable: $currdir = `pwd` print "Current directory is $currdir"; Yields: Current directory is /home/hermie Previous Lesson:Perl Basics Next Lesson:Perl Arguments

Arguments and Other Special Variables

Arguments are the values you pass to a Perl script. Each value on the command line after the name of the script will be assigned to the special variables$ARGV[0],$ARGV[1],$ARGV[2], and so on. The number of arguments passed to the script is stored in the$#ARGVvariable, and the full argument string is in the variable@ARGV. The name of the currently running program is stored in the$0variable. Let's try some examples working with arguments and other special variables. Create an executable script calledtestvars.plcontaining these lines: #!/usr/bin/perl print "My name is $0 \n"; print "First arg is: $ARGV[0] \n"; print "Second arg is: $ARGV[1] \n"; print "Third arg is: $ARGV[2] \n"; $num = $#ARGV + 1; print "How many args? $num \n"; print "The full argument string was: @ARGV \n"; Now if you run this script, here's what you'll see: $./testvars dogs can whistle My name is testvars.pl First arg is: dogs Second arg is: can Third arg is: whistle How many args? 3 The full argument string was: dogs can whistle Just a few notes about that example. I did say that the$#ARGVvariable contained the number of arguments, but I lied--sort of. Since the arguments are numbered starting at zero, you have to add one to the value of$#ARGVto get the actual number of arguments. It's a bit weird, but if you're a fan of the C language, it'll all seem quite normal. Also note that the@ARGVvariable doesn't start with a dollar sign. That's because it's anarrayvariable, as opposed to the regularscalarvariables we've worked with so far. An array can be thought of as a list of values, where each value is addressed by a scalar (dollar sign) variable and an index number in square brackets, as in$ARGV[0],$ARGV[1], and so on. Don't worry too much about arrays for now-that's a topic for more study on your own.

Previous Lesson:Perl Variables Next Lesson:Perl Logic

Você também pode gostar