Introduction to C++

69
Introduction to C++

description

Introduction to C++. Topics. C++ Structure Primitive Data Types I/O Casting Strings Control Flow. Objective. At the end of this lesson, students should be able to write simple C++ programs using the standard I/O library, the String class, and primitive data types. Introduction. - PowerPoint PPT Presentation

Transcript of Introduction to C++

Page 1: Introduction to C++

Introduction to C++

Page 2: Introduction to C++

Introducing C++

C++ StructurePrimitive Data TypesI/OCastingStringsControl Flow

Page 3: Introduction to C++

Objective

At the end of this lesson, students shouldbe able to write simple C++ programsusing the standard I/O library, the Stringclass, and primitive data types.

Page 4: Introduction to C++

Introduction

In CS1410 we will study the C++ programming language.

We do this for a number of reasons (1) We want our students to know at least 2 languages (2) C++ exposes some important ideas, like pointers, that are hidden from the programmer in other languages (3) Seeing the basic principles of programming used in a 2nd

language will significantly increase you programming skills

Page 5: Introduction to C++

Starting Point

We will start out assuming that you know C#because that is what we teach in CS 1400.

If you learned another language in yourCS 1400 class, don’t worry. You’ll catch on.

Page 6: Introduction to C++

Review: A Simple C# Program

using System;

class Program{ // a constant const int SIZE = 5;

static void Main( ) {

// a local variable double average =32.5; // arithmetic double newValue = average * SIZE;

Console.WriteLine("The average value is {0}", average); Console.ReadLine(); }}

Page 7: Introduction to C++

Let’s Convert it to C++

using System;

class Program{ // a constant const int SIZE = 5;

static void Main( ) {

// a local variable double average =32.5; // arithmetic double newValue = average * SIZE;

Console.WriteLine("The average value is {0}", average); Console.ReadLine(); }}

Page 8: Introduction to C++

Let’s Convert it to C++

using System;

class Program{ // a constant const int SIZE = 5;

static void Main( ) {

// a local variable double average =32.5; // arithmetic double newValue = average * SIZE;

Console.WriteLine("The average value is {0}", average); Console.ReadLine(); }}

C++ is not a pure object orientedlanguage, so all code does not needto be enclosed inside of a class.

Page 9: Introduction to C++

Let’s Convert it to C++

using System;

// a constant const int SIZE = 5;

static void Main( ) {

// a local variable double average =32.5; // arithmetic double newValue = average * SIZE;

Console.WriteLine("The average value is {0}", average); Console.ReadLine(); }

Main does not have to be static.in C++ it normally returns an int,and it spelled main (no capital M).

Main( ) always returns an integer.int main( )

return 0;

Page 10: Introduction to C++

Let’s Convert it to C++

using System;

// a constant const int SIZE = 5;

int main( ) {

// a local variable double average =32.5; // arithmetic double newValue = average * SIZE;

Console.WriteLine("The average value is {0}", average); Console.ReadLine(); return 0; }

The syntax of basic declarations,arithmetic, and control statementsare the same as in C#

Page 11: Introduction to C++

Let’s Convert it to C++

using System;

// a constant const int SIZE = 5;

int main( ) {

// a local variable double average =32.5; // arithmetic double newValue = average * SIZE;

Console.WriteLine("The average value is {0}", average); Console.ReadLine(); return 0; }

C++ I/O is much different from C#(we’ll discuss the details later)

cout << “The average value is “ << average << endl;

Page 12: Introduction to C++

Let’s Convert it to C++

using System;

// a constant const int SIZE = 5;

int main( ) {

// a local variable double average =32.5; // arithmetic double newValue = average * SIZE;

Console.ReadLine(); return 0; }

To keep the console window open, we’ll use a system call

cout << “The average value is “ << average << endl;system(“PAUSE”);

Page 13: Introduction to C++

Let’s Convert it to C++

using System;

// a constant const int SIZE = 5;

int main( ) {

// a local variable double average =32.5; // arithmetic double newValue = average * SIZE;

system(“PAUSE”); return 0; }

Namespaces are declared differentlyin C++. Everything we will use is inthe standard (std) namespace.

cout << “The average value is “ << average << endl;

using namespace std;

Page 14: Introduction to C++

Let’s Convert it to C++

using namespace std;

// a constant const int SIZE = 5;

int main( ) {

// a local variable double average =32.5; // arithmetic double newValue = average * SIZE;

system(“PAUSE”); return 0; }

Finally, we need to add a new pre-processor directive, that includesheader files that are required forour program to compile correctly.

The iostream header file is required when doing console I/O.

cout << “The average value is “ << average << endl;

#include <iostream>

Page 15: Introduction to C++

Here’s the Final C++ Program

using namespace std;

// a constant const int SIZE = 5;

int main( ) {

// a local variable double average =32.5; // arithmetic double newValue = average * SIZE;

system(“PAUSE”); return 0; }

cout << “The average value is “ << average << endl;

#include <iostream>

Page 16: Introduction to C++

Header Files

In a C++ program every .cpp file in the project is compiled on its own to produce an object file. Once all of the object files have been produced, they are linked together to create an executable (.exe) file. This means that one .cpp file has noclue of what is defined in the other .cpp files in the program.

So, how do the various bits and pieces of a program createdfrom multiple .cpp files communicate with each other?

Page 17: Introduction to C++

Header Files

Header files provide a way for you to advertise theconstants and function interfaces in your code, sothat others can link to your code without having to know the details of the implementation.

Page 18: Introduction to C++

Example

In the program we just developed, we have this statement:

cout << “The average value is “ << average << endl;

The name cout refers to an object of the ostream class.The compiler find out how the cout object works by lookingat the header file <iostream>. To tell the compiler to lookthere we write

#include <iostream>

Page 19: Introduction to C++

In this course, you should provide a header file for every.cpp file that you create. In the example we have beenworking on, there is only the .cpp file that contains main().The companion header file for this file should contain• Any #includes required by main( )• Any constants used by main( )• The function prologues and function prototypes for any stand-alone functions that reside in this file.

Page 20: Introduction to C++

A Good C++ Code Skeleton

// file prologue

#include “driver.h”int main( ){ // declare local variable variables here // C++ statements

system(“PAUSE”); return 0; }

// file prologue

#include <iostream>#include <string>using namespace std;

// constant declarations

// prologues and prototypes// for stand alone functions

driver.cppdriver.h

Page 21: Introduction to C++

Primitive Data Types

C++ has fewer primitive data types than does C#,but the primary ones that we will use are exactlythe same … int, double, bool, and char.

There is a major difference between C++ data typesand C# data types. In C++, the size of a data typeis determined by the underlying hardware, it is notdefined by the language.

Page 22: Introduction to C++

Assignment and Arithmetic workjust as they do in C#.

Page 23: Introduction to C++

C++ Input and Output

In place of C#s Console class, we need twoC++ Objects to do console input and output

Page 24: Introduction to C++

cincin is an object of the istream class. To use cin, you must #include iostream in your program.

This object represents the standard input stream. The cin object is created automatically for you.

keyboard buffercin program

keyboard buffer

Page 25: Introduction to C++

cout is an object of the ostream class. This objectrepresents the standard output stream. It

is also created automatically for you.

output buffercout program

cout

display buffer

Page 26: Introduction to C++

The Stream Insertion Operator, <<

a binary operator (it takes two operands)the left hand operand must be an output streamthe right hand operand

– is converted into text– the text data is then copied into the stream

Page 27: Introduction to C++

display buffer

int a = 5; a 0000 0000 0000 0101

the integer 5

0000 0000 0011 0101

the character 5

cout

cout << a;

5

Page 28: Introduction to C++

multiple pieces of data are output bycascading the << operator …

cout << “The answer is “ << a;

Page 29: Introduction to C++

If you want data to appear on a new line, you mustexplicitly add the newline character to the outputstream. There is no WriteLine operation.

Special characters are added to the streamusing the escape character \

\t\netc …

cout << “The answer is “ << a << ‘\n’;

Page 30: Introduction to C++

the endl stream manipulator can be added to the outputstream. It does two things:

It adds a new line to the stream.

It forces the buffer to be output

cout << “Hello” << endl;

Page 31: Introduction to C++

Formatting Numbers

Output formatting in C++ is quite different fromC#’s output formatting.

Page 32: Introduction to C++

To display a double or a float in standard decimal notation

cout.setf(ios::fixed);

setf( ) is a function in the cout object. It is responsible forsetting formatting flags. We will study these in much moredetail in a later section. In this case, we are setting theios::fixed flag. This makes the output appear as a normaldecimal number instead of in scientific notation.

cout.setf(ios::showpoint);

the ios::showpoint flag guarantees that a decimal pointwill be displayed in the output.

cout.precision(2);

the cout.precision( ) function determines how many digitswill be displayed after the decimal point.

The default formatting, is the“general” format. In this caseprecision defines the number ofdigits in total to be displayed

Page 33: Introduction to C++

Example

double price = 78.5;cout.setf(ios::fixed);cout.setf(ios::showpoint);cout.precison(2);cout << “The price is $” << price << endl;

Page 34: Introduction to C++

The stream extraction operator, >>

Also a binary operatorThe left operand must be an input streamAny initial white space is skipped, then the stream is read up

to the next white space character ( tab, space, new-line )If necessary, the text just read is converted to match the

type of the right operand. An error occurs if the conversion cannot be done.

The data is stored in the right operand

Page 35: Introduction to C++

keyboard buffercin

int a;cin >> a;

a

0000 0000 0011 0101

the character 5

0000 0000 0000 0101

5 72 hello

reading stops when white space is encountered

Page 36: Introduction to C++

In C#, we always read a string from theConsole, and then used a Parse method toconvert the string to the desired data type.

In C++, this conversion happens automatically.

However, no exception occurs if the conversioncannot be done.

Page 37: Introduction to C++

Failed Input

Consider the following:

A program contains the statements int number = 0; cin >> number

What happens if the user types the letter “t”?

Page 38: Introduction to C++

The stream extraction operator is not able toconvert the letter “t” into a proper integer value.Three important things happen, without warning:

1. No input occurs, so the variable number contains whatever value it had previously.

2. The letter “t” remains in the input buffer, so a subsequent read operation will try to read it again.

3. The object cin sets itself to a “failed” state, and subsequent input operations will all fail.

Page 39: Introduction to C++

Handling Failed Input

As noted, if input fails, no data is input.

We can detect when this happens by testing the state ofthe input stream object.

if (cin.fail( ) ) { cout << “Invalid input occurred”; . . . }

Page 40: Introduction to C++

There is a well known idiom in C++ that makeshandling failed input much easier. The expression

cin >> number;

has a value, which is the value of the cin object itself.if the value of cin is “good”, we can go ahead and process the data. The statement to do this looks like

if (cin >> number) { // process the input

}

Page 41: Introduction to C++

Recall that once the stream object fails, all subsequentread operations will fail. How do we fix that?

The stream objects have a member function namedclear( ), that resets the failed state back to good.

cin.clear( );

Page 42: Introduction to C++

Using the Stream State to Control a Loop

cout << “\nEnter an integer value (or ‘q’ to quit): “;while (cin >> number){ // process the data

}cin.clear( ); // clear the fail statestring dummyValue; // get the ‘q’ out of the buffercin >> dummyValue;. . .

This code will process user input until a non-integer value is typed:

Page 43: Introduction to C++

you can also cascade the stream extraction operator:

cin >> a >> b;

Page 44: Introduction to C++

You can control the size of an input field withthe setw( n ) stream manipulator.

cin >> setw(5) >> title;

But … keep in mind that this can leave data in the buffer.

Page 45: Introduction to C++

cin.get

The get function of the istream class works similarto the stream extraction operator. With no parameter,it gets one character from the input stream.

cin.get( );

Page 46: Introduction to C++

cin.ignore( )

This function reads in a character and ignoresit. The character read in is discarded.

cin.ignore( );

Page 47: Introduction to C++

This version of the function reads in n charactersand ignores them.

cin.ignore(n);

This version of the function reads in n charactersor until it encounters the delimiter character,and ignores the characters read.

cin.ignore(n, ‘\n’);

Page 48: Introduction to C++

Why is ignore useful? Try the following code…

int numItems;string description;

cout << “\nenter the number of items and description: “;cin >> numItems;getline(cin, description);

When prompted, enter the data on two lines.

Page 49: Introduction to C++

Suppose that the user enter 5 for thenumber of items. The contents of thestream object cin look like this:

5 nl

The steam object contains a pointer thatalways points to the next character to read.At this stage it is pointing to the 5. The newlinecharacter was put into the stream when the userpressed the Enter key.

Page 50: Introduction to C++

When this statement is executed

cin >> numItems;

5 nl

The character 5 is read from the stream, convertedinto the integer 5, and stored in the variable numItems.The pointer into the stream now points to the new line character.

Page 51: Introduction to C++

Now the user enters A p p l e s andpresses the Enter key. The stream looks like this:

5 nl A p p l e s nl

Page 52: Introduction to C++

Now the program executes this statement:

getline(cin, description);

5 nl

The getline command reads data until it encounters a new linecharacter. The characters it reads are stored in the stringvariable description. The new line character is discarded.

A p p l e s nl

Page 53: Introduction to C++

5 nl

The getline command found the newline character and quit. Nothing gets stored in the variable description. Thecharacters A p p l e remain in the stream.

A p p l e s nl

Page 54: Introduction to C++

int numItems;string description;

cout << “\nenter the number of items and description: “;cin >> numItems;cin.ignore( ); // gets rid of the newline charactergetline(cin, description);

When prompted, enter the data on two lines.

The Solution

Page 55: Introduction to C++

5 nl

The cin.ignore( ) command moves the stream pointerover 1 character, so the newline character is ignored.It now points to the A.

A p p l e s nl

Page 56: Introduction to C++

Now the program executes this statement:

getline(cin, description);

5 nl

The getline command reads data until it encounters a new linecharacter. The characters A p p l e s are reads from the Stream and stored in the string variable description.

The new line character is discarded.

A p p l e s nl

Page 57: Introduction to C++

In C++, you can use the same style of castas you did in C#, but the preferred way tocast in C++ is to write, for example

Casting

int number = static_cast<int> (myDoubleValue);

Page 58: Introduction to C++

Strings

C++ has a string class what is similar to C#’s string class.

Page 59: Introduction to C++

Declaring a String(you must #include <string>)

string myName;

string myName = “Prof. deBry”;

Page 60: Introduction to C++

Reading a line into a string

This function is similar to cin.get( )except thatit reads an entire line of data, including spaces,and the data is stored in a string object. This isthe preferred way of reading in a line of data.It is equivalent to C#’s ReadLine method.

getline(cin, stringName);

Page 61: Introduction to C++

Additional Notes on the String Class

Use + to concatenate two strings

Use the member function size( ) to get the length of a string

The [ ] operator can be used to access or modify individualcharacters of a string. No bounds checking is performed.

The c_str( ) member function returns a char* based string.

Page 62: Introduction to C++

The C11 Numeric Conversion Functions

The C++11 standard contains new functions to convertthe contents of a string into a numeric value. These aresimilar to C#’s Parse methods.

stoi – converts a string to an int

stod– converts a string to a double

+ 6 more for the other C++ numeric data types

Page 63: Introduction to C++

The C11 Numeric Conversion Functions

These functions attempt to convert the first part ofa string into a numeric value. If a conversioncannot be performed, an invalid_argumentexception is thrown.

Page 64: Introduction to C++

Use getline and the numeric conversion functionsin the string class to avoid the problems with cin.

Page 65: Introduction to C++

int numItems;string description;string inputValue;

cout << “\nenter the number of items and description: “;getline(cin inputValue); // get the user input in the stringnumItems = stoi(inputValue). // convert it to an integergetline(cin, description);

Alternate Solution

This is similar to the way you read an integer in C#.

Page 66: Introduction to C++

C++ Control Flow

With a few minor exceptions, the statements that controlflow through a C++ program look and work the same as they do in C#

Page 67: Introduction to C++

Switch

In C#, each case must contain a break statement. Itis illegal to drop through from one case to the next.

Page 68: Introduction to C++

switch (num){case 1: a = a + 5; b = b + 3;case 2: a = a + 6; b = b + 4;case 3: a = a – 7; b = b – 1;}

if num = 3, only this code executes

if num = 2, then this code executes

if num =1, thenthis code executes

This is valid code in C++

Page 69: Introduction to C++

There is no foreach statement in C++

Instead, C++ uses a range based for. Itlooks like this:

int a[ ] = {1, 2, 3};for(int n : x){ cout << n << endl;}