Lecture 10. Command line arguments Character handling library void* String manipulation (copying, searching, etc.)

Size: px
Start display at page:

Download "Lecture 10. Command line arguments Character handling library void* String manipulation (copying, searching, etc.)"

Transcription

1 Lecture 10 Class string Namespaces Preprocessor directives Macros Conditional compilation Command line arguments Character handling library void* <cctype> TNCG18(C++): Lec 10 1 Class string Template class basic_string String manipulation (copying, searching, etc.) typedef basic_string< char > string; #include <string> string initialization string s1( "Hello" ); string s2( 8, 'x' ); s2 gets xxxxxxxx string month = "March ; Implicitly calls constructor (not the assignment operator); string month( March ); TNCG18(C++): Lec

2 string features Class string Not necessarily null terminated length member function: s1.length() Use [] to access individual characters: s1[0] 0 to length-1 string not a pointer Many member functions take start position and length Stream extraction White space delimited input. cin >> stringobject; getline(cin, s); Delimited by newline TNCG18(C++): Lec 10 3 string Assignment and Concatenation Assignment s2 = s1; Makes a separate copy s2.assign(s1); Same as s2 = s1; mystring.assign(s, start, N); Copies N characters from s, beginning at index start Several overloaded versions of assign() See Individual characters s2[0] = s3[2]; s2.at(0) = s3.at(2); // performs range check TNCG18(C++): Lec

3 string Assignment and Concatenation Range checking s3.at( index ); Returns character at index Can throw out_of_range exception [] has no range checking Concatenation s3.append( "pet" ); s3 += "pet"; Both add "pet" to end of s3 s3.append( s1, start, N ); Appends N characters from s1, beginning at index start Other overloaded versions of append exist TNCG18(C++): Lec 10 5 Comparing strings Overloaded operators ==,!=, <, >, <= and >= Return bool s1.compare(s2) Returns positive if s1 lexicographically greater Compares letter by letter 'B' lexicographically greater than 'A' Returns negative if less, zero if equal s1.compare(start1,length1, s2, start2, length2) Compare portions of s1 and s2 s1.compare(start1, length1, s2) Compare portion of s1 with all of s2 TNCG18(C++): Lec

4 Substrings and Swapping strings Function substr gets substring s1.substr( start, N ); Gets N characters, beginning with index start Returns substring string str= "We think in generalities, but we live in details."; string str2; str2 = str.substr (12,12); // "generalities" s1.swap(s2); Switch contents of two strings TNCG18(C++): Lec 10 7 Member functions string Characteristics s1.size() and s1.length() Number of characters in string s1.capacity() Number of elements that can be stored without reallocation s1.max_size() Maximum possible string size If exceeded, a length_error exception is thrown s1.empty() Returns true if empty s1.resize(newlength) Resizes string to newlength TNCG18(C++): Lec

5 Finding Strings and Characters in a string Find functions If found, index returned If not found, string::npos returned Public static constant in class string s1.find( s2 ) s1.find( s2, pos ) s1.rfind( s2 ) Searches right-to-left s1.find_first_of( s2 ) Returns first occurrence of any character in s2 s1.find_first_of( "abcd" ) Returns index of first 'a', 'b', 'c' or 'd' TNCG18(C++): Lec 10 9 Finding Strings and Characters in a string Find functions s1.find_last_of( s2 ) Finds last occurrence of any character in s2 s1.find_first_not_of( s2 ) Finds first character NOT in s2 s1.find_last_not_of( s2 ) Finds last character NOT in s2 TNCG18(C++): Lec

6 Replacing Characters in a string s1.erase( start ) Erase from index start to end of string, including start Replace s1.replace( begin, N, s2) begin: index in s1 to start replacing N: number of characters to replace s2: replacement string s1.replace( begin, N, s2, index, num ) index: element in s2 where replacement begins num: number of elements to use when replacing Replacement can overwrite characters TNCG18(C++): Lec An Example int position = string1.find(. ); //replace all periods with two semicolons //Note: this will overwrite characters while ( position!= string::npos ) { string1.replace(position, 2, ;; ); position = string1.find(., position+1); } TNCG18(C++): Lec

7 Inserting Characters into a string s1.insert( index, s2 ) Inserts s2 at index It does not overwrite other characters s1.insert( index, s2, index2, N ); Inserts substring of s2 at position index Substring is N characters, starting at index2 Example: String s1( beginning end ); String s2 ( middle ); S1.insert(10, s2); cout << s1; // beginning middle end TNCG18(C++): Lec Conversion to C-Style char* Strings Conversion functions strings not necessarily null-terminated s1.copy( ptr, N, index ) Copies N characters into the array ptr (char*) Starts at location index of s1 Add explicitly null as last character s1.c_str() Returns const char* Null terminated s1.data() Returns const char* NOT null-terminated TNCG18(C++): Lec

8 Namespaces Program has identifiers in different scopes Sometimes scopes overlap, lead to problems Namespace defines scope Place identifiers and variables within namespace Access with namespace_name::member Note guaranteed to be unique namespace Name { contents } Unnamed namespaces are global Need no qualification Namespaces can be nested TNCG18(C++): Lec using statement Namespaces using namespace namespace_name; Members of that namespace can be used without preceding namespace_name:: Can also be used with individual member Examples using namespace std; using namespace std::cout Can write cout instead of std::cout TNCG18(C++): Lec

9 1 // Fig. 22.3: fig22_03.cpp 2 // Demonstrating namespaces. 3 #include <iostream> 4 5 using namespace std; // use std namespace 6 7 int integer1 = 98; // global variable 8 9 // create namespace Example 10 namespace Example { // declare two constants and one variable 13 const double PI = ; 14 const double E = ; 15 int integer1 = 8; void printvalues(); // prototype // nested namespace 20 namespace Inner { // define enumeration 23 enum Years { FISCAL1 = 1990, FISCAL2, FISCAL3 }; } // end Inner 26 TNCG18(C++): Lec } // end Example // create unnamed namespace 30 namespace { 31 double doubleinunnamed = 88.22; // declare variable } // end unnamed namespace int main() 36 { 37 // output value doubleinunnamed of unnamed namespace 38 cout << "doubleinunnamed = " << doubleinunnamed; // output global variable 41 cout << "\n(global) integer1 = " << integer1; // output values of Example namespace 44 cout << "\npi = " << Example::PI << "\ne = " 45 << Example::E << "\ninteger1 = " 46 << Example::integer1 << "\nfiscal3 = " 47 << Example::Inner::FISCAL3 << endl; return 0; } // end main How useful can it be unnamed namespaces? TNCG18(C++): Lec

10 Preprocessing Occurs before program compiled All directives begin with # Inclusion of external files #include <iostream> Definition of symbolic constants Macros Conditional compilation Conditional execution Directives not C++ statements Do not end with ; TNCG18(C++): Lec The #include Preprocessor Directive #include directive Puts copy of file in place of directive Seen many times in example code Two forms #include <filename> For standard library header files Searches pre-designated directories #include "filename.h" Searches in current directory Normally used for programmer-defined files TNCG18(C++): Lec

11 The #define Preprocessor Directive: Symbolic Constants Format #define identifier replacement-text #define PI When program compiled, all occurrences PI are replaced by Advantages: takes no memory Disadvantage: name PI not be seen by debugger Everything to right of identifier replaces text #define PI= Replaces PI with "= An alternative const double PI = ; Probably, an error!! TNCG18(C++): Lec Macro Macros Operation specified in #define Intended for legacy C programs Macro without arguments Treated like a symbolic constant Macro with arguments Arguments substituted for replacement text Macro expanded Performs a text substitution No data type checking TNCG18(C++): Lec

12 Macros: Example #define CIRCLE_AREA( x ) ( PI * ( x ) * ( x ) ) area = CIRCLE_AREA( 4 ); becomes area = ( * ( 4 ) * ( 4 ) ); Use parentheses Without them, #define CIRCLE_AREA( x ) PI * x * x area = CIRCLE_AREA( c + 2 ); becomes area = * c + 2 * c + 2; which evaluates incorrectly May not give the right Passing arguments with side effects results!!! area = CIRCLE_AREA( ++i ); Use inline functions. TNCG18(C++): Lec inline Functions inline double CIRCLE_AREA( double x ) { return PI * x * x; } Advise the compiler to replace function calls with functions code To help reduce function call overhead Use with small functions Inline funtions appear in header files (.h) Type checking is performed TNCG18(C++): Lec

13 Conditional Compilation Structure similar to if #ifndef FLAG #if!defined( FLAG ) #define FLAG #define FLAG 1 //code //code #endif #endif Determines if symbolic constant FLAG is defined If FLAG defined, #defined FLAG 1 is skipped All code until #endif is ignored Every #if ends with #endif TNCG18(C++): Lec Conditional Compilation A header file Limousine.h may start with #ifndef LIMOUSIN_H #define LIMOUSIN_H Avoid multiple inclusions of Limousine.h class Limousin : public Taxi { public: Limousin( string = """", int = 0 ); }; #endif File1.h File2.cpp #include Limousine.h #include Limousine.h #include File1.h TNCG18(C++): Lec

14 Conditional Compilation Debugging #define DEBUG 1 #ifdef DEBUG cerr << "Variable x = " << x << endl; #endif Defining DEBUG enables code After code corrected Remove #define statement Debugging statements are now ignored TNCG18(C++): Lec assert is a macro Assertions Header <cassert> assert( x <= 10 ); Tests value of an expression If 0 (false) prints error message, calls abort Terminates program, prints line number and file Good for checking for illegal values If 1 (true), program continues as normal To remove assert statements No need to delete them manually #define DEBUG All subsequent assert statements ignored TNCG18(C++): Lec

15 Using Command-Line Arguments Can pass arguments to main in UNIX/DOS Include parameters in main int main( int argc, char* argv[] ) int argc char** Number of arguments char *argv[] Array of strings that contains command-line arguments Example: $ copy input.txt output.txt argc: 3 argv[0]: "copy" argv[1]: "input.txt" argv[2]: "output.txt" TNCG18(C++): Lec And More Character-handling library #include <cctype> Includes functions that perform tests and manipulations in char data int isdigit(int c); int toupper(int c); Pointer-based string conversions #include <cstdlib> double atof(const char *p); double d = atof( 99.6 ); double strtod(const char *p1, char **p2); const char str1[] = 99.9% pass 10%. char *str2; double d = (str1, &str2); Search for more information about it in cplusplus.com TNCG18(C++): Lec

16 void *ptr; void* Can be assigned any other type of pointer int i = 5; ptr = &i; Pointers to void cannot be derreferenced cout << *ptr; \\Compiler ERROR!! Pointers to void can be casted to any other type of pointer Be careful with its use, then!! cout << *(char *)ptr; Use to make functions more generic, i.e. accept different types of arguments TNCG18(C++): Lec

Lecture 10. To use try, throw, and catch Constructors and destructors Standard exception hierarchy new failures

Lecture 10. To use try, throw, and catch Constructors and destructors Standard exception hierarchy new failures Lecture 10 Class string Exception Handling To use try, throw, and catch Constructors and destructors Standard exception hierarchy new failures Class template auto_ptr Lec 10 Programming in C++ 1 Class

More information

OBJECT ORIENTED PROGRAMMING USING C++

OBJECT ORIENTED PROGRAMMING USING C++ OBJECT ORIENTED PROGRAMMING USING C++ Chapter 17 - The Preprocessor Outline 17.1 Introduction 17.2 The #include Preprocessor Directive 17.3 The #define Preprocessor Directive: Symbolic Constants 17.4 The

More information

Class string and String Stream Processing Pearson Education, Inc. All rights reserved.

Class string and String Stream Processing Pearson Education, Inc. All rights reserved. 1 18 Class string and String Stream Processing 2 18.1 Introduction C++ class template basic_string Provides typical string-manipulation operations Defined in namespace std typedefs For char typedef basic_string

More information

Lecture 9. Introduction

Lecture 9. Introduction Lecture 9 File Processing Streams Stream I/O template hierarchy Create, update, process files Sequential and random access Formatted and raw processing Namespaces Lec 9 Programming in C++ 1 Storage of

More information

CSC 330 Object Oriented Design. Namespaces

CSC 330 Object Oriented Design. Namespaces CSC 330 Object Oriented Design Namespaces 1 Introduction C++ was developed in early 1980s by Bjarne Stroustrup (AT&T). It was formulated by adding object oriented (and other) features to C, and removing

More information

Introduction. namespaces Program has identifiers in different scopes Sometimes scopes overlap, lead to problems. Accessing the Variables.

Introduction. namespaces Program has identifiers in different scopes Sometimes scopes overlap, lead to problems. Accessing the Variables. Introduction CSC 330 Object Oriented Design s C++ was developed in early 1980s by Bjarne Stroustrup (AT&T). It was formulated by adding object oriented (and other) features to C, and removing a few bad

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 Data that is formatted and written to a sequential file as shown in Section 17.4 cannot be modified without the risk of destroying other data in the file. For example, if the name White needs to be changed

More information

COMP322 - Introduction to C++

COMP322 - Introduction to C++ COMP322 - Introduction to C++ Winter 2011 Lecture 2 - Language Basics Milena Scaccia School of Computer Science McGill University January 11, 2011 Course Web Tools Announcements, Lecture Notes, Assignments

More information

Chapter 15 - C++ As A "Better C"

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

what are strings today: strings strings: output strings: declaring and initializing what are strings and why to use them reading: textbook chapter 8

what are strings today: strings strings: output strings: declaring and initializing what are strings and why to use them reading: textbook chapter 8 today: strings what are strings what are strings and why to use them reading: textbook chapter 8 a string in C++ is one of a special kind of data type called a class we will talk more about classes in

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

COMP322 - Introduction to C++ Lecture 02 - Basics of C++ COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Discussion 1H Notes (Week 4, April 22) TA: Brian Choi Section Webpage:

Discussion 1H Notes (Week 4, April 22) TA: Brian Choi Section Webpage: Discussion 1H Notes (Week 4, April 22) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 Passing Arguments By Value and By Reference So far, we have been passing in

More information

Other Topics. Objectives. In this chapter you ll:

Other Topics. Objectives. In this chapter you ll: Other Topics 23 Objectives In this chapter you ll: Understand storage classes and storage duration. Use const_cast to temporarily treat a const object as a non-const object. Use mutable members in const

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

Computer Programming

Computer Programming Computer Programming Dr. Deepak B Phatak Dr. Supratik Chakraborty Department of Computer Science and Engineering Session : C++ Standard Library The string Class Dr. Deepak B. Phatak & Dr. Supratik Chakraborty,

More information

Chapter 2. Procedural Programming

Chapter 2. Procedural Programming Chapter 2 Procedural Programming 2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic

More information

Dodatak D Standardna string klasa

Dodatak D Standardna string klasa Dodatak D Standardna klasa from: C++ annotations, by Frank C. Brokken, University of Groningen, ISBN 90 367 0470. The C programming language offers rudimentary support: the ASCII-Z terminated series of

More information

CSCI 1061U Programming Workshop 2. C++ Basics

CSCI 1061U Programming Workshop 2. C++ Basics CSCI 1061U Programming Workshop 2 C++ Basics 1 Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment Statements Console Input/Output

More information

Programming C++ Lecture 6. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor

Programming C++ Lecture 6. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor Programming C++ Lecture 6 Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor Jennifer.sartor@elis.ugent.be S Friends 2 Friends of Objects S Classes sometimes need friends. S Friends are defined outside

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

G52CPP C++ Programming Lecture 14. Dr Jason Atkin

G52CPP C++ Programming Lecture 14. Dr Jason Atkin G52CPP C++ Programming Lecture 14 Dr Jason Atkin 1 Last Lecture Automatically created methods: A default constructor so that objects can be created without defining a constructor A copy constructor used

More information

std::string Quick Reference Card Last Revised: August 18, 2013 Copyright 2013 by Peter Chapin

std::string Quick Reference Card Last Revised: August 18, 2013 Copyright 2013 by Peter Chapin std::string Quick Reference Card Last Revised: August 18, 2013 Copyright 2013 by Peter Chapin Permission is granted to copy and distribute freely, for any purpose, provided the copyright notice above is

More information

AN OVERVIEW OF C++ 1

AN OVERVIEW OF C++ 1 AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

Working with Strings. Lecture 2. Hartmut Kaiser. hkaiser/spring_2015/csc1254.html

Working with Strings. Lecture 2. Hartmut Kaiser.  hkaiser/spring_2015/csc1254.html Working with Strings Lecture 2 Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/spring_2015/csc1254.html Abstract This lecture will look at strings. What are strings? How can we input/output

More information

Introduction to C++ Introduction to C++ 1

Introduction to C++ Introduction to C++ 1 1 What Is C++? (Mostly) an extension of C to include: Classes Templates Inheritance and Multiple Inheritance Function and Operator Overloading New (and better) Standard Library References and Reference

More information

Part 3: Function Pointers, Linked Lists and nd Arrays

Part 3: Function Pointers, Linked Lists and nd Arrays Part 3: Function Pointers, Linked Lists and nd Arrays Prof. Dr. Ulrik Schroeder C++ - Einführung ins Programmieren WS 03/04 http://learntech.rwth-aachen.de/lehre/ws04/c++/folien/index.html Pointer to functions

More information

CSCE 110 PROGRAMMING FUNDAMENTALS

CSCE 110 PROGRAMMING FUNDAMENTALS CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class Prof. amr Goneid, AUC 1 Dictionaries(1): A Key Table Class Prof. Amr Goneid, AUC 2 A Key Table

More information

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Programming with C++ as a Second Language

Programming with C++ as a Second Language Programming with C++ as a Second Language Week 2 Overview of C++ CSE/ICS 45C Patricia Lee, PhD Chapter 1 C++ Basics Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives Introduction to

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

Functions and Recursion

Functions and Recursion Functions and Recursion 1 Storage Classes Scope Rules Functions with Empty Parameter Lists Inline Functions References and Reference Parameters Default Arguments Unary Scope Resolution Operator Function

More information

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Chapter 1. C++ Basics. Copyright 2010 Pearson Addison-Wesley. All rights reserved Chapter 1 C++ Basics Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment

More information

CSCE 110 PROGRAMMING FUNDAMENTALS

CSCE 110 PROGRAMMING FUNDAMENTALS CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 8. Characters & Strings Prof. amr Goneid, AUC 1 Characters & Strings Prof. amr Goneid, AUC 2 Characters & Strings Characters & their

More information

III. Classes (Chap. 3)

III. Classes (Chap. 3) III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,

More information

CS2141 Software Development using C/C++ C++ Basics

CS2141 Software Development using C/C++ C++ Basics CS2141 Software Development using C/C++ C++ Basics Integers Basic Types Can be short, long, or just plain int C++ does not define the size of them other than short

More information

Tokens, Expressions and Control Structures

Tokens, Expressions and Control Structures 3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type

More information

Ch. 10, The C++ string Class

Ch. 10, The C++ string Class Ch. 10, The C++ string Class 1 Constructing a String You can create an empty string using string s no-arg constructor like this one: string newstring; You can create a string object from a string value

More information

Operator Overloading in C++ Systems Programming

Operator Overloading in C++ Systems Programming Operator Overloading in C++ Systems Programming Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. Global Functions Overloading

More information

Chapter 1 Introduction to Computers and C++ Programming

Chapter 1 Introduction to Computers and C++ Programming Chapter 1 Introduction to Computers and C++ Programming 1 Outline 1.1 Introduction 1.2 What is a Computer? 1.3 Computer Organization 1.7 History of C and C++ 1.14 Basics of a Typical C++ Environment 1.20

More information

This watermark does not appear in the registered version - Slide 1

This watermark does not appear in the registered version -   Slide 1 Slide 1 Chapter 1 C++ Basics Slide 2 Learning Objectives Introduction to C++ Origins, Object-Oriented Programming, Terms Variables, Expressions, and Assignment Statements Console Input/Output Program Style

More information

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents:

Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language. Dr. Amal Khalifa. Lecture Contents: Structured Programming Using C++ Lecture 2 : Introduction to the C++ Language Dr. Amal Khalifa Lecture Contents: Introduction to C++ Origins Object-Oriented Programming, Terms Libraries and Namespaces

More information

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above P.G.TRB - COMPUTER SCIENCE Total Marks : 50 Time : 30 Minutes 1. C was primarily developed as a a)systems programming language b) general purpose language c) data processing language d) none of the above

More information

2 nd Week Lecture Notes

2 nd Week Lecture Notes 2 nd Week Lecture Notes Scope of variables All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous

More information

CS 376b Computer Vision

CS 376b Computer Vision CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves

More information

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011 CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011 Date: 01/18/2011 (Due date: 01/20/2011) Name and ID (print): CHAPTER 6 USER-DEFINED FUNCTIONS I 1. The C++ function pow has parameters.

More information

Appendix A. The Preprocessor

Appendix A. The Preprocessor Appendix A The Preprocessor The preprocessor is that part of the compiler that performs various text manipulations on your program prior to the actual translation of your source code into object code.

More information

The Foundation of C++: The C Subset An Overview of C p. 3 The Origins and History of C p. 4 C Is a Middle-Level Language p. 5 C Is a Structured

The Foundation of C++: The C Subset An Overview of C p. 3 The Origins and History of C p. 4 C Is a Middle-Level Language p. 5 C Is a Structured Introduction p. xxix The Foundation of C++: The C Subset An Overview of C p. 3 The Origins and History of C p. 4 C Is a Middle-Level Language p. 5 C Is a Structured Language p. 6 C Is a Programmer's Language

More information

A A B U n i v e r s i t y

A A B U n i v e r s i t y A A B U n i v e r s i t y Faculty of Computer Sciences O b j e c t O r i e n t e d P r o g r a m m i n g Week 4: Introduction to Classes and Objects Asst. Prof. Dr. M entor Hamiti mentor.hamiti@universitetiaab.com

More information

Definition Matching (10 Points)

Definition Matching (10 Points) Name SOLUTION Closed notes and book. If you have any questions ask them. Write clearly and make sure the case of a letter is clear (where applicable) since C++ is case sensitive. There are no syntax errors

More information

C++ basics Getting started with, and Data Types.

C++ basics Getting started with, and Data Types. C++ basics Getting started with, and Data Types pm_jat@daiict.ac.in Recap Last Lecture We talked about Variables - Variables, their binding to type, storage etc., Categorization based on storage binding

More information

Programming. C++ Basics

Programming. C++ Basics Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

More information

C Style Strings. Lecture 11 COP 3014 Spring March 19, 2018

C Style Strings. Lecture 11 COP 3014 Spring March 19, 2018 C Style Strings Lecture 11 COP 3014 Spring 2018 March 19, 2018 Recap Recall that a C-style string is a character array that ends with the null character Character literals in single quotes a, \n, $ string

More information

Characters, c-strings, and the string Class. CS 1: Problem Solving & Program Design Using C++

Characters, c-strings, and the string Class. CS 1: Problem Solving & Program Design Using C++ Characters, c-strings, and the string Class CS 1: Problem Solving & Program Design Using C++ Objectives Perform character checks and conversions Knock down the C-string fundamentals Point at pointers and

More information

Introduction to Programming

Introduction to Programming Introduction to Programming session 5 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel s slides Sahrif University of Technology Outlines

More information

C Legacy Code Topics. Objectives. In this appendix you ll:

C Legacy Code Topics. Objectives. In this appendix you ll: cppfp2_appf_legacycode.fm Page 1 Monday, March 25, 2013 3:44 PM F C Legacy Code Topics Objectives In this appendix you ll: Redirect keyboard input to come from a file and redirect screen output to a file.

More information

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12 CS31 Discussion 1E Jie(Jay) Wang Week3 Oct.12 Outline Problems from Project 1 Review of lecture String, char, stream If-else statements Switch statements loops Programming challenge Problems from Project

More information

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O Outline EDAF30 Programming in C++ 2. Introduction. More on function calls and types. Sven Gestegård Robertz Computer Science, LTH 2018 1 Function calls and parameter passing 2 Pointers, arrays, and references

More information

Object Oriented Design

Object Oriented Design Object Oriented Design Chapter 9 Initializing a non-static data member in the class definition is a syntax error 1 9.2 Time Class Case Study In Fig. 9.1, the class definition is enclosed in the following

More information

CS11 Advanced C++ Lecture 2 Fall

CS11 Advanced C++ Lecture 2 Fall CS11 Advanced C++ Lecture 2 Fall 2006-2007 Today s Topics C++ strings Access Searching Manipulation Converting back to C-style strings C++ streams Error handling Reading unformatted character data Simple

More information

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers and Arrays CS 201 This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers Powerful but difficult to master Used to simulate pass-by-reference

More information

Jim Lambers ENERGY 211 / CME 211 Autumn Quarter Programming Project 2

Jim Lambers ENERGY 211 / CME 211 Autumn Quarter Programming Project 2 Jim Lambers ENERGY 211 / CME 211 Autumn Quarter 2007-08 Programming Project 2 This project is due at 11:59pm on Friday, October 17. 1 Introduction In this project, you will implement functions in order

More information

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information

CS11 Introduction to C++ Spring Lecture 8

CS11 Introduction to C++ Spring Lecture 8 CS11 Introduction to C++ Spring 2013-2014 Lecture 8 Local Variables string getusername() { string user; } cout user; return user;! What happens to user when function

More information

COP 3014: Fall Final Study Guide. December 5, You will have an opportunity to earn 15 extra credit points.

COP 3014: Fall Final Study Guide. December 5, You will have an opportunity to earn 15 extra credit points. COP 3014: Fall 2017 Final Study Guide December 5, 2017 The test consists of 1. 15 multiple choice questions - 30 points 2. 2 find the output questions - 20 points 3. 2 code writing questions - 30 points

More information

Cpt S 122 Data Structures. Introduction to C++ Part II

Cpt S 122 Data Structures. Introduction to C++ Part II Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function

More information

IV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard

IV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard IV. Stacks 1 A. Introduction 1. Consider the problems on pp. 170-1 (1) Model the discard pile in a card game (2) Model a railroad switching yard (3) Parentheses checker () Calculate and display base-two

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2 Discussion 1E Jie(Jay) Wang Week 10 Dec.2 Outline Dynamic memory allocation Class Final Review Dynamic Allocation of Memory Recall int len = 100; double arr[len]; // error! What if I need to compute the

More information

Object Oriented Programming COP3330 / CGS5409

Object Oriented Programming COP3330 / CGS5409 Object Oriented Programming COP3330 / CGS5409 Dynamic Allocation in Classes Review of CStrings Allocate dynamic space with operator new, which returns address of the allocated item. Store in a pointer:

More information

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things. A Appendix Grammar There is no worse danger for a teacher than to teach words instead of things. Marc Block Introduction keywords lexical conventions programs expressions statements declarations declarators

More information

QUIZ. What are 3 differences between C and C++ const variables?

QUIZ. What are 3 differences between C and C++ const variables? QUIZ What are 3 differences between C and C++ const variables? Solution QUIZ Source: http://stackoverflow.com/questions/17349387/scope-of-macros-in-c Solution The C/C++ preprocessor substitutes mechanically,

More information

G52CPP C++ Programming Lecture 17

G52CPP C++ Programming Lecture 17 G52CPP C++ Programming Lecture 17 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last Lecture Exceptions How to throw (return) different error values as exceptions And catch the exceptions

More information

Lecture 5 Files and Streams

Lecture 5 Files and Streams Lecture 5 Files and Streams Introduction C programs can store results & information permanently on disk using file handling functions These functions let you write either text or binary data to a file,

More information

Assignment 5: MyString COP3330 Fall 2017

Assignment 5: MyString COP3330 Fall 2017 Assignment 5: MyString COP3330 Fall 2017 Due: Wednesday, November 15, 2017 at 11:59 PM Objective This assignment will provide experience in managing dynamic memory allocation inside a class as well as

More information

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018 C++ Basics Lecture 2 COP 3014 Spring 2018 January 8, 2018 Structure of a C++ Program Sequence of statements, typically grouped into functions. function: a subprogram. a section of a program performing

More information

Bruce Merry. IOI Training Dec 2013

Bruce Merry. IOI Training Dec 2013 IOI Training Dec 2013 Outline 1 2 3 Outline 1 2 3 You can check that something is true using assert: #include int main() { assert(1 == 2); } Output: test_assert: test_assert.cpp:4: int main():

More information

The University of Nottingham

The University of Nottingham The University of Nottingham SCHOOL OF COMPUTER SCIENCE A LEVEL 2 MODULE, AUTUMN SEMESTER 2009-2010 C/C++ for Java Programmers Time allowed TWO hours Candidates may complete the front cover of their answer

More information

Course "Data Processing" Name: Master-1: Nuclear Energy Session /2018 Examen - Part A Page 1

Course Data Processing Name: Master-1: Nuclear Energy Session /2018 Examen - Part A Page 1 Examen - Part A Page 1 1. mydir directory contains three files: filea.txt fileb.txt filec.txt. How many files will be in the directory after performing the following operations: $ ls filea.txt fileb.txt

More information

String Objects: The string class library

String Objects: The string class library String Objects: The string class library Lecture 23 COP 3014 Spring 2017 March 7, 2017 C-strings vs. string objects In C++ (and C), there is no built-in string type Basic strings (C-strings) are implemented

More information

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information

Due Date: See Blackboard

Due Date: See Blackboard Source File: ~/2315/45/lab45.(C CPP cpp c++ cc cxx cp) Input: under control of main function Output: under control of main function Value: 4 Integer data is usually represented in a single word on a computer.

More information

More Functions. Pass by Value. Example: Exchange two numbers. Storage Classes. Passing Parameters by Reference. Pass by value and by reference

More Functions. Pass by Value. Example: Exchange two numbers. Storage Classes. Passing Parameters by Reference. Pass by value and by reference Pass by Value More Functions Different location in memory Changes to the parameters inside the function body have no effect outside of the function. 2 Passing Parameters by Reference Example: Exchange

More information

Copyright 2003 Pearson Education, Inc. Slide 1

Copyright 2003 Pearson Education, Inc. Slide 1 Copyright 2003 Pearson Education, Inc. Slide 1 Chapter 11 Strings and Vectors Created by David Mann, North Idaho College Copyright 2003 Pearson Education, Inc. Slide 2 Overview An Array Type for Strings

More information

Chapter 18 - C++ Operator Overloading

Chapter 18 - C++ Operator Overloading Chapter 18 - C++ Operator Overloading Outline 18.1 Introduction 18.2 Fundamentals of Operator Overloading 18.3 Restrictions on Operator Overloading 18.4 Operator Functions as Class Members vs. as friend

More information

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING Dr. Shady Yehia Elmashad Outline 1. Introduction to C++ Programming 2. Comment 3. Variables and Constants 4. Basic C++ Data Types 5. Simple Program: Printing

More information

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE? 1. Describe History of C++? The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the languages Stroustrup had the opportunity

More information

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces Basic memory model Using functions Writing functions Basics Prototypes Parameters Return types Functions and memory Names and namespaces When a program runs it requires main memory (RAM) space for Program

More information

Programmazione. Prof. Marco Bertini

Programmazione. Prof. Marco Bertini Programmazione Prof. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Hello world : a review Some differences between C and C++ Let s review some differences between C and C++ looking

More information

C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

C++ As A Better C Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan. C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2013 Fall Outline 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.5

More information

CS31 Discussion 1E. Jie(Jay) Wang Week5 Oct.27

CS31 Discussion 1E. Jie(Jay) Wang Week5 Oct.27 CS31 Discussion 1E Jie(Jay) Wang Week5 Oct.27 Outline Project 3 Debugging Array Project 3 Read the spec and FAQ carefully. Test your code on SEASnet Linux server using the command curl -s -L http://cs.ucla.edu/classes/fall16/cs31/utilities/p3tester

More information

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy CSCI 334: Principles of Programming Languages Lecture 18: C/C++ Homework help session will be tomorrow from 7-9pm in Schow 030A instead of on Thursday. Instructor: Dan Barowy HW6 and HW7 solutions We only

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

C Functions. Object created and destroyed within its block auto: default for local variables

C Functions. Object created and destroyed within its block auto: default for local variables 1 5 C Functions 5.12 Storage Classes 2 Automatic storage Object created and destroyed within its block auto: default for local variables auto double x, y; Static storage Variables exist for entire program

More information