Affichage des articles dont le libellé est C language. Afficher tous les articles

C++ Strings – A Reference / PDF



C++ Strings – A Reference / PDF

C++ Strings – A Reference / PDF









 Click here for  Download PDF / FREE





C++ Strings – A Reference / PDF

0

C++ Strings


C++ Strings


C++ Strings





Sample of the pdf document 






C++ Strings

One of the most useful data types supplied in the C++ libraries is the string. A string is a
variable that stores a sequence of letters or other characters, such as "Hello" or "May 10th is my birthday!". Just like the other data types, to create a string we first declare it, then we can store a value in it.

string testString;
testString = "This is a string.";

We can combine these two statements into one line:

string testString = "This is a string.";

Often, we use strings as output, and cout works exactly like one would expect:
cout << testString << endl;

will print the same result as
cout << "This is a string." << endl;

In order to use the string data type, the C++ string header must be included at the top of the program. Also, you’ll need to include using namespace std; to make the short name string visible instead of requiring the cumbersome std::string. (As a side note, std is a C++ namespace for many pieces of functionality that are provided in standard C++ libraries. 

For the purposes of this class, you won't need to otherwise know
about namespaces.) Thus, you would have the following #include's in your program in order to use the string type.

#include
using namespace std;

Basic Operations

Let’s go into specifics about the string manipulations you’ll be doing the most.

Counting the number of characters in a string. The length method returns the number of characters in a string, including spaces and punctuation. Like many of the string operations, length is a member function, and we invoke member functions using dot notation. The string that is the receiver is to the left of the dot, the member function we are invoking is to the right, (e.g. str.length()). In such an expression, we are requesting the length from the variable str.


example program:

#include
#include
using namespace std;

#include "console.h"
int main() {
string small, large;
small = "I am short";
large = "I, friend, am a long and elaborate string indeed";
cout << "The short string is " << small.length()
<< " characters." << endl;
cout << The long string is " << large.length()
<< " characters." << endl;
return 0;
}
output:
The short string is 10 characters.
The long string is 48 characters.
Accessing individual characters. Using square brackets, you can access individual characters within a string as if it’s a char array. Positions within a string str are numbered from 0 through str.length() - 1. You can read and write to characters
within a string using [].

example program:

#include
#include

using namespace std;
#include "console.h"
int main() {
string test;
test = "I am Q the omnipot3nt";
char ch = test[5]; // ch is 'Q'
test[18] = 'e'; // we correct misspelling of omnipotent
cout << test << endl;
cout << "ch = " << ch << endl;
return 0;
}..................




 Click here for  Download PDF / FREE



C++ Strings



0

C++ Strings / PDF

C++ Strings / PDF




C++ Strings / PDF






Sample of the pdf document 









C++ String Variables

The standard C++ library provides an object string type to complement the string
literals used earlier:

string Name1, // must #include
Name2;
A string variable may be assigned the value of a string literal or another string variable:

Name1 = “Bjarne Stroustrup”;
Name2 = Name1;
string myString;
myString = ‘N’;
const int asciiN =78;
myString = asciiN; // string equals “N”


String Initialization

A string variable may be initialized at the point of declaration:
string Greet1 = “Hello”,
Greet2 = Greet1;

It is not, however, legal to assign a char or int value to a string in the declaration:

string String1 = ‘N’, // illegal
String2 = 78; // illegal
Since it would be legal to assign ‘N’ to String1, you might ask why it is illegal
to initialize String1 with ‘N’ in the declaration of String1. The full reason would take us into a discussion of the notion of a class in C++, a topic not covered in this course.

Suffice it to say at this point that the statements above are true.


It is not legal to have a line break within a string literal in C++:

string BadString = “It is as a tale told by an idiot, // not
full of sound and fury, // legal
signifying nothing.”;
. . . however, somewhat perversely, this is OK:

string LongString = “It is as a tale told by an idiot, ”
“full of sound and fury, ”
“signifying nothing.”;
And, of course, it is legal for a string literal to contain a newline character:

string Prompt = “Type your user id below and press :\n”;



String Output


A string variable may be printed by inserting it to an output stream, just as with any simple variable:

string Greetings = “Hello, world!”;
cout << Greetings << endl;

Just as with string literals, no whitespace padding is provided automatically, so:

cout << Greetings << “It’s a wonderful day!”;
would print:
Hello, world!It’s a wonderful day!
Of course, you can provide whitespace yourself:
cout << Greetings << “ ” << “It’s a wonderful day!”;..............








 Click here for  Download PDF / FREE


C++ Strings / PDF



0

Tutorial C++ : Summary of the C++ language / PDF


Tutorial C++ : Summary of the C++ language / PDF


Tutorial C++ : Summary of the C++ language / PDF



Sample of the pdf document 









Comments:             // rest of line is ignored

I/O:                             cin >> i;          // no & needed
         cout << “i = “ << i << endl;
            manipulators:           dec, hex, setw(int), setfill(int), left, right

Types:      bool  b;            // either true or false
   enum day_of_week {sun,mon,tue,wed,thu,fri,sat};
   day_of_week d;
   const int MAX 999;   // use const instead of #define

Assignment operator:
            Assignment also has a value associated with it - the rhs of the assignment
   j = (p=3);           // j is assigned 3

Comma operator:
     for (i=0,j=0;i<10 ...="..." i="i" j="j" o:p="o:p">
            An expression involving the comma operator has the value of the right-hand expression.
   k = (i=4),(j=5);     // k is assigned 5

Conditional operator:
   m = (n>10)? 4 : 5;

break, continue:
            Flow around a loop may be altered by the use of:
            break - ends the loop
            continue - restarts the loop - increment of a for loop, test of a while loop.

Declarations:
            Variables may be declared anywhere. They will exist until the enclosing block terminates.

Default arguments:
            Arguments to functions may be given default values:
int fct(int i=5,int j=0);
           
Function overloading:
            Versions of the same function may exist, if the arguments or return types are different:
int max(int m, int n);
float max(float x, float y);

            The compiler chooses which function to call in the following order:
                        look for an exact match
                        look for a match by promoting short->long, float->double etc
                        look for a match by converting float->int

Inline functions:
            The overhead of calling a function can be removed if the function is declared inline.
inline cube(int j) {return j*j*j;}

            The compiler will not create inline functions for recursive functions.
            Code size will increase if large inline functions are used.

Call by reference:
            Arguments that are changed within a function, no longer need to be passed as pointers. Arguments that are passed using call-by-reference can be altered by the function:
   int m=3;
   change_it(m);
   cout << m;           // m is now 4
   ...
void change_it(int &n) {    //n refers back to m
   n = 4;
}

Scope:
            Static local variables retain their value from one function call to another.
            Static global variables are only visible to functions within that particular source file.
            Global variables can be made visible to other source files using extern.
            Functions are known across all source files by default
            Static functions are known only to the particular source file.

            C++ uses namespace to further restrict scope:
namespace XXX {
   void fct(void);
}
            fct is only known within the namespace XXX.
            To access the function either use the scope operator ::
XXX::fct();

            or allow all functions within the namespace to be used directly with:
using namespace XXX;

            Header files that obey the namespace convention have no .h.
            Normal C functions are all within the namespace std

Memory allocation:
            new and delete are better ways of allocating and freeing dynamic memory than malloc and free
int *p,*q;
p = new int;
q = new int[20];
delete p;
delete [] q;       //special form to delete arrays......







 Click here for  Download PDF / FREE

Tutorial C++ : Summary of the C++ language / PDF


0

C++ Language Tutorial / PDF


C++ Language Tutorial / PDF
C++ Language Tutorial / PDF






Table of Contents:







-----------------------------------

Sample of the pdf document 





Structure of a program



Probably the best way to start learning a programming language is by writing a program. Therefore, here is our first program:
// my first program in C++
 
#include 
using namespace std;
 
int main ()
{
  cout << "Hello World!";
  return 0;
}
Hello World!

The first panel shows the source code for our first program. The second one shows the result of the program once compiled and executed. The way to edit and compile a program depends on the compiler you are using. Depending on whether it has a Development Interface or not and on its version. Consult the compilers section and the manual or help included with your compiler if you have doubts on how to compile a C++ console program.

The previous program is the typical program that programmer apprentices write for the first time, and its result is the printing on screen of the "Hello World!" sentence. It is one of the simplest programs that can be written in C++, but it already contains the fundamental components that every C++ program has. We are going to look line by line at the code we have just written:

// my first program in C++
This is a comment line. All lines beginning with two slash signs (//) are considered comments and do not have any effect on the behavior of the program. The programmer can use them to include short explanations or observations within the source code itself. In this case, the line is a brief description of what our program is.
#include
Lines beginning with a pound sign (#) are directives for the preprocessor. They are not regular code lines with expressions but indications for the compiler's preprocessor. In this case the directive #include tells the preprocessor to include the iostream standard file. This specific file (iostream) includes the declarations of the basic standard input-output library in C++, and it is included because its functionality is going to be used later in the program.
using namespace std;
All the elements of the standard C++ library are declared within what is called a namespace, the namespace with the name std. So in order to access its functionality we declare with this expression that we will be using these entities. This line is very frequent in C++ programs that use the standard library, and in fact it will be included in most of the source codes included in these tutorials.
int main ()
This line corresponds to the beginning of the definition of the main function. The main function is the point by where all C++ programs start their execution, independently of its location within the source code. It does not matter whether there are other functions with other names defined before of after it - the instructions contained within this function's definition will always be the first ones to be executed in any C++ program. For that same reason, it is essential that all C++ programs have a main function.
The word main is followed in the code by a pair of parentheses (()). That is because it is a function declaration: In C++, what differentiates a function declaration from other types of expressions are these parentheses that follow its name. Optionally, these parentheses may enclose a list of parameters within them.
Right after these parentheses we can find the body of the main function enclosed in braces ({}). What is contained within these braces is what the function does when it is executed.
cout << "Hello World";
This line is a C++ statement. A statement is a simple or compound expression that can actually produce some effect. In fact, this statement performs the only action that generates a visible effect in our first program.
cout represents the standard output stream in C++, and the meaning of the entire statement is to insert a sequence of characters (in this case the Hello World sequence of characters) into the standard output stream (which usually is the screen).
cout is declared in the iostream standard file within the std namespace, so that's why we needed to include that specific file and to declare that we were going to use this specific namespace earlier in our code.
Notice that the statement ends with a semicolon character (;). This character is used to mark the end of the statement and in fact it must be included at the end of all expression statements in all C++ programs (one of the most common syntax errors is indeed to forget to include some semicolon after a statement).
return 0;
The return statement causes the main function to finish. return may be followed by a return code (in our example is followed by the return code 0). A return code of 0 for the main function is generally interpreted as the program worked as expected without any errors during its execution. This is the most usual way to end a C++ program.
You may have noticed that not all the lines of this program perform actions when the code is executed. There were lines containing only comments (those beginning by //). There were lines with directives for the compiler's preprocessor (those beginning by #). Then there were lines that began the declaration of a function (in this case, the main function) and, finally lines with statements (like the insertion into cout), which were all included within the block delimited by the braces ({}) of the main function.

The program has been structured in different lines in order to be more readable, but in C++, we do not have strict rules on how to separate instructions in different lines. For example, instead of

int main ()
{
  cout << " Hello World ";
  return 0;
}

We could have written:

int main () { cout << "Hello World"; return 0; }

All in just one line and this would have had exactly the same meaning as the previous code.
In C++, the separation between statements is specified with an ending semicolon (;) at the end of each one, so the separation in different code lines does not matter at all for this purpose. We can write many statements per line or write a single statement that takes many code lines. The division of code in different lines serves only to make it more legible and schematic for the humans that may read it.
Let us add an additional instruction to our first program:

// my second program in C++
 
#include 
 
using namespace std;
 
int main ()
{
  cout << "Hello World! ";
  cout << "I'm a C++ program";
  return 0;
}
Hello World! I'm a C++ program

In this case, we performed two insertions into cout in two different statements. Once again, the separation in different lines of code has been done just to give greater readability to the program, since main could have been perfectly valid defined this way:


int main () { cout << " Hello World! "; cout << " I'm a C++ program "; return 0; } 

We were also free to divide the code into more lines if we considered it more convenient:

int main ()
{
  cout <<
    "Hello World!";
  cout
    << "I'm a C++ program";
  return 0;
}

And the result would again have been exactly the same as in the previous examples.
Preprocessor directives (those that begin by #) are out of this general rule since they are not statements. They are lines read and discarded by the preprocessor and do not produce any code by themselves. Preprocessor directives must be specified in their own line and do not have to end with a semicolon (;)....... 










 Click here for  Download PDF / FREE




C++ Language Tutorial / PDF

1

Introduction to C++ Programming/ PDF




Introduction to C++  Programming/ PDF



Introduction to C++  Programming/ PDF






Sample of the pdf document 









Why do you need to learn “old” compiled languages?


  • Because C, C++, and Fortran (77/95) are the most  efficient existing tools for intensive numerical computing
  • Because tons of fast and well-tested codes are available in Fortran, C/C++
  • Newer languages have emphasized simplicity and reliability – at the cost of computational efficiency
  • To get speed, you need to dive into the details of compiled languages, and this course is a first, gentle step

C language 

  • C is a dominating language in Unix and Windows environments
  • The C syntax has inspired lots of popular languages (Awk, C++, Java, Perl, Python, Ruby)
  • Numerous tools (numerical libraries, e.g., MPI) are written in C; interfacing them requires C knowledge
  • C is extremely portable; “all” machines can compile and run C programs
  • C is very low level and close to the machine
  • Unlimited possibilities; one can do anything in C
  • Programmers of high-level languages often get confused by strange/unexpected errors in C

C++ language 

C++ extends C with
  • nicer syntax:
              - declare variables wherever you want
              - in/out function arguments use references (instead of pointers)
  • classes for implementing user-defined data types
  • a standard library (STL) for frequently used data types (list, stack, queue, vector, hash, string, complex, ...)
  • object-oriented programming
  • generic programming, i.e., parameterization of variable types via templates
  • exceptions for error handling
  • C is a subset of C++........







 Click here for  Download PDF / FREE

Introduction to C++  Programming/ PDF



1

Tags