Introduction to C++. Introducing C++ C++ Structure Primitive Data Types I/O Casting Strings Control Flow.

Slides:



Advertisements
Similar presentations
CPS120: Introduction to Computer Science INPUT/OUTPUT.
Advertisements

Chapter 10.
Computer Science 1620 Variables and Memory. Review Examples: write a program that calculates and displays the average of the numbers 45, 69, and 106.
Input/Output Main Memory istream ostream Disk Drive Keyboard Scanner Disk Drive Monitor Printer stream = sequence of bytes.
1 September 6, 2005CS150 Introduction to Computer Science I What Actions Do We Have Part 1 CS150 Introduction to Computer Science I.
CSC 200 Lecture 2 Matt Kayala 1/25/06. Lecture Objectives More detailed intro to C++ Variables, Expressions, and Assignment Statements Console Input/Output.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
Basic Elements of C++ Chapter 2.
Input and Output in Console Mode UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) ADNAN BABAR MT14028 CR
CSCI 1730 January 17 th, 2012 © by Pearson Education, Inc. All Rights Reserved.
Expressions and Interactivity Chapter 3. 2 The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Often.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
© Janice Regan, CMPT 128, Sept CMPT 128: Introduction to Computing Science for Engineering Students C++ Basic Input and output.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 2 Introduction to C++
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CSC 270 – Survey of Programming Languages C++ Lecture 1 : C++ As A Better C.
Chapter 3 Assignment, Formatting, and Interactive Input C++ for Engineers and Scientists Third Edition.
Chapter 1 C++ Basics Copyright © 2012 Pearson Addison-Wesley. All rights reserved.
File I/O ifstreams and ofstreams Sections 11.1 &
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
Slide 1. Slide 2 Chapter 1 C++ Basics Slide 3 Learning Objectives  Introduction to C++  Origins, Object-Oriented Programming, Terms  Variables, Expressions,
TEXT FILES. CIN / COUT REVIEW  We are able to read data from the same line or multiple lines during successive calls.  Remember that the extraction.
Chapter 3: Assignment, Formatting, and Interactive Input.
C++ for Engineers and Scientists Second Edition Chapter 3 Assignment, Formatting, and Interactive Input.
4. Input/Output Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 C++ Input/Output: Streams The.
A first program 1. #include 2. using namespace std; 3. int main() { 4. cout
Programming Fundamentals. Summary of previous lectures Programming Language Phases of C++ Environment Variables and Data Types.
C++ for Engineers and Scientists Second Edition Chapter 7 Completing the Basics.
Operating System Using setw and setprecision functions Using setiosflags function Using cin function Programming 1 DCT
PROGRAM ESSENTIALS. TOKENS  SMALLEST UNITS OF A PROGRAM LANGUAGE  Special Symbols  Mathematical Operators  Punctuation  Word Symbols  Key Words.
Chapter 9: Completing the Basics. In this chapter, you will learn about: – Exception handling – Exceptions and file checking – The string class – Character.
CMPSC 121- Spring 2015 Lecture 6 January 23, 2015.
1 What is a Named Constant? A named constant is a location in memory that we can refer to by an identifier, and in which a data value that cannot be changed.
Chapter 3 Assignment, Formatting, and Interactive Input C++ for Engineers and Scientists Third Edition.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
More about strings in C++. String member functions The next three slides present information about functions that are members of the C++ string class.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
Chapter 4 Strings and Screen I/O. Objectives Define strings and literals. Explain classes and objects. Use the string class to store strings. Perform.
Introduction Every program takes some data as input and generate processed data as out put . It is important to know how to provide the input data and.
Chapter 1 C++ Basics Copyright © 2016 Pearson, Inc. All rights reserved.
Chapter 1.2 Introduction to C++ Programming
Introduction to C++ (Extensions to C)
C++ Basic Input and Output (I/O)
Chapter Topics The Basics of a C++ Program Data Types
Chapter 2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
CPS120: Introduction to Computer Science
CPS120: Introduction to Computer Science
Basic Elements of C++.
Chapter 2 part #3 C++ Input / Output
Basic Elements of C++ Chapter 2.
Input and Output Chapter 3.
Standard Input/Output Streams
Standard Input/Output Streams
Input/Output Handouts: Quiz 2, Unit 3 practice sheets.
Introduction to C++ Programming
Basic Input and Output C++ programs can read and write information using streams A simple input stream accepts typed data from a keyboard A simple output.
Chapter 3: Input/Output
Chapter 3 Input output.
Introduction to C++ Programming
Chapter 2: Introduction to C++.
Fundamental Programming
Chapter 2 part #3 C++ Input / Output
C++ for Engineers and Scientists Second Edition
Chapter 1 c++ structure C++ Input / Output
Programming Fundamental-1
Presentation transcript:

Introduction to C++

Introducing C++ 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 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 2 nd language will significantly increase you programming skills

Starting Point We will start out assuming that you know C# because that is what we teach in CS If you learned another language in your CS 1400 class, don’t worry. You’ll catch on.

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(); }

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(); }

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 oriented language, so all code does not need to be enclosed inside of a class.

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;

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 statements are the same as in 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;

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”);

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 differently in C++. Everything we will use is in the standard (std) namespace. cout << “The average value is “ << average << endl; using namespace std;

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 includes header files that are required for our program to compile correctly. The iostream header file is required when doing console I/O. cout << “The average value is “ << average << endl; #include

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

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 no clue of what is defined in the other.cpp files in the program. So, how do the various bits and pieces of a program created from multiple.cpp files communicate with each other?

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

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 looking at the header file. To tell the compiler to look there we write #include

In this course, you should provide a header file for every.cpp file that you create. In the example we have been working 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.

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 using namespace std; // constant declarations // prologues and prototypes // for stand alone functions driver.cpp driver.h

Primitive Data Types C++ has fewer primitive data types than does C#, but the primary ones that we will use are exactly the same … int, double, bool, and char. There is a major difference between C++ data types and C# data types. In C++, the size of a data type is determined by the underlying hardware, it is not defined by the language.

Assignment and Arithmetic work just as they do in C#.

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

cin cin 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 buffer cin program keyboard buffer

cout is an object of the ostream class. This object represents the standard output stream. It is also created automatically for you. output buffer cout program cout display buffer

The Stream Insertion Operator, << a binary operator (it takes two operands) the left hand operand must be an output stream the right hand operand –is converted into text –the text data is then copied into the stream

display buffer int a = 5; a the integer the character 5 cout cout << a; 5

multiple pieces of data are output by cascading the << operator … cout << “The answer is “ << a;

If you want data to appear on a new line, you must explicitly add the newline character to the output stream. There is no WriteLine operation. Special characters are added to the stream using the escape character \ \t \n etc … cout << “The answer is “ << a << ‘\n’;

the endl stream manipulator can be added to the output stream. It does two things: It adds a new line to the stream. It forces the buffer to be output cout << “Hello” << endl;

Formatting Numbers Output formatting in C++ is quite different from C#’s output formatting.

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 for setting formatting flags. We will study these in much more detail in a later section. In this case, we are setting the ios::fixed flag. This makes the output appear as a normal decimal number instead of in scientific notation. cout.setf(ios::showpoint); the ios::showpoint flag guarantees that a decimal point will be displayed in the output. cout.precision(2); the cout.precision( ) function determines how many digits will be displayed after the decimal point. The default formatting, is the “general” format. In this case precision defines the number of digits in total to be displayed

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

The stream extraction operator, >> Also a binary operator The left operand must be an input stream Any 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

keyboard buffer cin int a; cin >> a; a the character hello reading stops when white space is encountered

In C#, we always read a string from the Console, and then used a Parse method to convert the string to the desired data type. In C++, this conversion happens automatically. However, no exception occurs if the conversion cannot be done.

Failed Input Consider the following: A program contains the statements int number = 0; cin >> number What happens if the user types the letter “t”?

The stream extraction operator is not able to convert 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.

Handling Failed Input As noted, if input fails, no data is input. We can detect when this happens by testing the state of the input stream object. if (cin.fail( ) ) { cout << “Invalid input occurred”;... }

There is a well known idiom in C++ that makes handling 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 }

Recall that once the stream object fails, all subsequent read operations will fail. How do we fix that? The stream objects have a member function named clear( ), that resets the failed state back to good. cin.clear( );

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 state string dummyValue; // get the ‘q’ out of the buffer cin >> dummyValue;... This code will process user input until a non-integer value is typed:

you can also cascade the stream extraction operator : cin >> a >> b;

You can control the size of an input field with the setw( n ) stream manipulator. cin >> setw(5) >> title; But … keep in mind that this can leave data in the buffer.

cin.get The get function of the istream class works similar to the stream extraction operator. With no parameter, it gets one character from the input stream. cin.get( );

cin.ignore( ) This function reads in a character and ignores it. The character read in is discarded. cin.ignore( );

This version of the function reads in n characters and ignores them. cin.ignore(n); This version of the function reads in n characters or until it encounters the delimiter character, and ignores the characters read. cin.ignore(n, ‘\n’);

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.

Suppose that the user enter 5 for the number of items. The contents of the stream object cin look like this: 5nl The steam object contains a pointer that always points to the next character to read. At this stage it is pointing to the 5. The newline character was put into the stream when the user pressed the Enter key.

When this statement is executed cin >> numItems; 5nl The character 5 is read from the stream, converted into the integer 5, and stored in the variable numItems. The pointer into the stream now points to the new line character.

Now the user enters A p p l e s and presses the Enter key. The stream looks like this: 5nlA p p l e s nl

Now the program executes this statement: getline(cin, description); 5nl The getline command reads data until it encounters a new line character. The characters it reads are stored in the string variable description. The new line character is discarded. A p p l e s nl

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

int numItems; string description; cout << “\nenter the number of items and description: “; cin >> numItems; cin.ignore( ); // gets rid of the newline character getline(cin, description); When prompted, enter the data on two lines. The Solution

5nl The cin.ignore( ) command moves the stream pointer over 1 character, so the newline character is ignored. It now points to the A. A p p l e s nl

Now the program executes this statement: getline(cin, description); 5nl The getline command reads data until it encounters a new line character. 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

In C++, you can use the same style of cast as you did in C#, but the preferred way to cast in C++ is to write, for example Casting int number = static_cast (myDoubleValue);

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

Declaring a String (you must #include ) string myName; string myName = “Prof. deBry”;

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

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 individual characters of a string. No bounds checking is performed. The c_str( ) member function returns a char* based string.

The C11 Numeric Conversion Functions The C++11 standard contains new functions to convert the contents of a string into a numeric value. These are similar 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

The C11 Numeric Conversion Functions These functions attempt to convert the first part of a string into a numeric value. If a conversion cannot be performed, an invalid_argument exception is thrown.

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

int numItems; string description; string inputValue; cout << “\nenter the number of items and description: “; getline(cin inputValue); // get the user input in the string numItems = stoi(inputValue). // convert it to an integer getline(cin, description); Alternate Solution This is similar to the way you read an integer in C#.

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

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

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, then this code executes This is valid code in C++

There is no foreach statement in C++ Instead, C++ uses a range based for. It looks like this: int a[ ] = {1, 2, 3}; for(int n : x) { cout << n << endl; }