Character Functions & Manipulators Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10

Similar documents
More on Strings in C++ Arrays CS 16: Solving Problems with Computers I Lecture #11

Review of Important Topics in CS1600. Functions Arrays C-strings

More on File I/O Strings in C++ CS 16: Solving Problems with Computers I Lecture #10

Introduc)on to Arrays in C++ Review for Midterm #2 CS 16: Solving Problems with Computers I Lecture #12

File I/O and String Manipula3ons CS 16: Solving Problems with Computers I Lecture #11

Vectors and Pointers CS 16: Solving Problems with Computers I Lecture #13

Programming with Arrays Intro to Pointers CS 16: Solving Problems with Computers I Lecture #11

Arrays 2 CS 16: Solving Problems with Computers I Lecture #12

File Input / Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #9

File I/O CS 16: Solving Problems with Computers I Lecture #9

More Examples Using Functions and Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #6

Learning Objectives. Introduction to Arrays. Arrays in Functions. Programming with Arrays. Multidimensional Arrays

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

Overloading Functions & Command Line Use in C++ CS 16: Solving Problems with Computers I Lecture #6

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

Compiling C++ Programs Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Exercises with Linked Lists CS 16: Solving Problems with Computers I Lecture #15

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

Getting started with C++ (Part 2)

What we will learn about this week: Declaring and referencing arrays. arrays as function arguments. Arrays

More on Arrays CS 16: Solving Problems with Computers I Lecture #13

Chapter Overview. I/O Streams as an Introduction to Objects and Classes. I/O Streams. Streams and Basic File I/O. Objects

Algorithms for Arrays Vectors Pointers CS 16: Solving Problems with Computers I Lecture #14

Linked Lists CS 16: Solving Problems with Computers I Lecture #16

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

File Input/Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #10

BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18)

CS 31 Review Sheet. Tau Beta Pi - Boelter Basics 2. 2 Working with Decimals 2. 4 Operators 3. 6 Constants 3.

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Array Session 9

More on Func*ons Command Line Arguments CS 16: Solving Problems with Computers I Lecture #8

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

Design and Debug: Essen.al Concepts CS 16: Solving Problems with Computers I Lecture #8

Design and Debug: Essen.al Concepts Numerical Conversions CS 16: Solving Problems with Computers Lecture #7

Compiling with Multiple Files The Importance of Debugging CS 16: Solving Problems with Computers I Lecture #7

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff

BITG 1113: Array (Part 1) LECTURE 8

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Definition Matching (10 Points)

C++ Arrays. Arrays: The Basics. Areas for Discussion. Arrays: The Basics Strings and Arrays of Characters Array Parameters

(More) Fun with Pointers and Linked Lists! CS 16: Solving Problems with Computers I Lecture #17

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types.

Week 3: File I/O and Formatting 3.7 Formatting Output

Call-by-Type Functions in C++ Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #5

Exercise 1.1 Hello world

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

Agenda / Learning Objectives: 1. Map out a plan to study for mid-term Review the C++ operators up to logical operators. 3. Read about the tips

CS490: Problem Solving in Computer Science Lecture 3: Input/Output

System Design and Programming II

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved.

Func%ons in C++ Part 2 CS 16: Solving Problems with Computers I Lecture #5

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Advanced Flow Control CS 16: Solving Problems with Computers I Lecture #5

Lab # 02. Basic Elements of C++ _ Part1

Chapter 2: Basic Elements of C++

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

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

CSCE 110 PROGRAMMING FUNDAMENTALS

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

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

CMPS 221 Sample Final

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

Fundamentals of Programming CS-110. Lecture 2

21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std;

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

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections

CPE Summer 2015 Exam I (150 pts) June 18, 2015

Engineering Problem Solving with C++, Etter

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

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

Chapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved

CSI33 Data Structures

Pre- Defined Func-ons in C++ Review for Midterm #1

Numerical Conversions Intro to Strings in C/C++ CS 16: Solving Problems with Computers I Lecture #8

CSc Introduc/on to Compu/ng. Lecture 17 Edgardo Molina Fall 2011 City College of New York

Objectives. In this chapter, you will:

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

UEE1302 (1102) F10: Introduction to Computers and Programming

Sample Code: OUTPUT Daily Highs & Lows

I/O Streams and Standard I/O Devices (cont d.)

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

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

Flow Control in C++ Condi&onals & Loops CS 16: Solving Problems with Computers I Lecture #4

CS 103 Unit 14 - Streams

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

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

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

Lecture (07) Arrays. By: Dr. Ahmed ElShafee. Dr. Ahmed ElShafee, ACU : Fall 2015, Programming I

pointers + memory double x; string a; int x; main overhead int y; main overhead

C++ PROGRAMMING SKILLS Part 4: Arrays

Chapter 9. Strings. 國立雲林科技大學資訊工程研究所張傳育 (Chuan Yu Chang ) 博士

Absolute C++ Walter Savitch

UNIT- 3 Introduction to C++

What s in a file, what s in a string?

C++ For Science and Engineering Lecture 15

CPSC 427: Object-Oriented Programming

Transcription:

Character Functions & Manipulators Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10 Ziad Matni Dept. of Computer Science, UCSB

Lecture Outline Useful character manipulators & functions Arrays in C++ 5/8/18 Matni, CS16, Sp18 2

Member Functions: get and getline See demo files: get_example.cpp getline_example.cpp Allow you to use input streams that include white-spaces Unlike cin, which separates inputs by white-spaces Recall: white-space = space, tab, newline characters.get char c_fin, c_cin; ifstream inf; inf.get(c_fin); cin.get(c_cin);.getline string fstring, cin_string; ifstream inf; getline(inf, fstring); getline(cin, cin_string); 5/8/18 Matni, CS16, Sp18 3

getline function For standard inputs, cin is fine: but it ignores space, tabs, and newlines Sometimes, you want to get the entire line of data! And stop at the newline Best to use the function getline for that purpose. You have to include the <iostream> library (which you likely already do!) Popular Usage: getline(ifstream_object, string); getline(cin, string); 5/8/18 Matni, CS16, Sp18 4

Additional Note About getline You can customize what character a getline stops getting info You can define the character delimiter By default, that s a newline char Example: getline(cin, VariableX, m ) //stops at the char m If the standard input is Hello, I must be going, then VariableX will be Hello, I 5/8/18 Matni, CS16, Fa17 5

Character Functions Several predefined functions exist to facilitate working with characters The cctype library is required for most of them #include <cctype> using namespace std; 5/8/18 Matni, CS16, Sp18 6

The toupper Function toupper returns the argument's upper case character toupper('a') returns 'A' toupper('a') returns 'A' DOES NOT WORK WITH STRINGS! IT S FOR CHARACTERS ONLY! 5/8/18 Matni, CS16, Sp18 7

The tolower Function Similar to toupper function tolower returns the argument's lower case character tolower('a') returns 'a' tolower('a') returns 'a' 5/8/18 Matni, CS16, Sp18 8

The isspace Function isspace returns true if the argument is a whitespace So, isspace(' ') returns true, so does isspace( \n ) Example: if (isspace(next) ) cout << '-'; else cout << next; (spaces, tabs, and newlines) Prints a '-' if next contains a space, tab, or newline character 5/8/18 Matni, CS16, Sp18 9

5/8/18 10

Character Manipulators Work Too! Include <cctype> to use with, for example, toupper() string s = hello ; s[0] = toupper(s[0]); cout << s; // Will display Hello or to use with tolower() string s = HELLO ; for (int i=0; i < 5; i++) s[i] = tolower(s[i]); cout << s; // Will display hello 5/8/18 Matni, CS16, Sp18 11

Manipulators A type of function called in a nontraditional way Manipulators, in turn, call member functions May or may not have arguments to them Used after the insertion operator (<<) as if the manipulator function call is an output item 5/8/18 Matni, CS16, Sp18 12

The setw Manipulator setw sets spaces for output: only effective for one use Found in the library <iomanip> Example: cout << "Start" << setw(4) << 10 << setw(4) << 20 << setw(6) << 30; produces: Start 10 20 30 2 Spaces 4 Spaces The 1 st setw(4) ensures 4 spaces between Start" and 10, INCLUSIVE of the spaces taken up by 10. The 2 nd setw(4) ensures 4 spaces between 10 and 20, INCLUSIVE of the spaces taken up by 20. The 3 rd setw(6) ensures 6 spaces between 20 and 30, INCLUSIVE of the space taken up by 30. 5/8/18 Matni, CS16, Sp18 13

Converting Data Types in C++ stoi to_string stoi() String-to-Integer conversion Found in <string> library. Takes string as argument and returns int type. Example: int x = stoi( 66 ) // x = 66 If the string is NOT a number representation, it will cause a runtime error! to_string() Number-to-String conversion Found in <string> library. Takes int or double as argument and returns string type. Example: string y = to_string(6.32) // y = 6.32 5/8/18 Matni, CS16, Sp18 14

Converting Data Types in C++ Combining Characters with Strings Consider this code using C++ Strings: string msg1 = "Hello", msg2 = "World"; char sp = ' '; // space character string msg3 = msg1 + msg2; string msg4 = msg1 + sp + msg2; string msg4 = msg1 + sp + msg2[0]; string msg4 = msg1[0] + sp + msg2[0]; Compiles! Also Compiles! Also Compiles! Does NOT Compile! You can create a string that is a concatenation of strings + characters You CANNOT create a string out of only characters! Concatenation is just for strings - not for characters. 5/8/18 Matni, CS16, Sp18 15

ARRAYS 5/8/18 Matni, CS16, Sp18 16

Introduction to Arrays An array is used to process a collection of data of the same type Examples: A list of people s last names A list of numerical measurements Why do we need arrays? Imagine keeping track of 1000 test scores in memory! How would you name all the variables? How would you process each of the variables? 5/8/18 Matni, CS16, Sp18 17

Declaring an Array int score[5]; // Declares an array of ints called score that has 5 elements: // score[0], score[1], score[2], score[3], score[4] subscript or index Note the size of the array is the highest index value + 1 Because indexing in C++ starts at 0, not 1 The index can be an integer data type variable also 5/8/18 Matni, CS16, Sp18 18

Loops And Arrays for-loops are commonly used to step through arrays First index is 0 Example: int max = 9, size = 5; for (i = 0; i < size; i++) cout << max score[i] << endl; Last index is (size 1) displays the difference between each score and the maximum score stored in an array 5/8/18 Matni, CS16, Sp18 19

Declaring An Array When you declare an array, you MUST declare its size as well! { } used for full-array initializations int MyArray[5]; //Array declared has 5 non-initialized elements int MyArray[] = {1, 2, 5, 7, 0}; // Array declared has 5 initialized elements int MyArray[5] = {1, 2, 5, 7, 0}; // This is ok too! 5/8/18 Matni, CS16, Sp18 20

Initializing Arrays It s recommended to initialize an array when it is declared The values for the indexed variables are enclosed in braces and separated by commas Example: int children[3] = {2, 12, 1}; Is equivalent to: int children[3]; children[0] = 2; children[1] = 12; children[2] = 1; 5/8/18 Matni, CS16, Sp18 21

Constants and Arrays You can use variables as indices in arrays, BUT NOT to declare them! However, you can use constants to declare size of an array Example: const int NUMBER_OF_STUDENTS = 50; // can change this later int score[number_of_students]; for ( int i = 0; i < NUMBER_OF_STUDENTS; i++) cout << score[i] << endl; To make this code work for any number of students, simply change the value of the constant in the 1 st line 5/8/18 Matni, CS16, Sp18 22

When reserving memory space for an array in C++, the compiler needs to know just 3 things: 1. A starting address (location) 2. How many elements in array 3. What data type the array elements are If the compiler needs to determine the address of a[3], for example It starts at a[0] (it knows this address!) It counts past enough memory for three integers to find a[3] 5/8/18 Matni, CS16, Sp18 23

Array Index Out of Range A common error by programmers is using a nonexistent index Index values for int a[6] are the values 0 through 5 An index value that s not allowed by the array declaration is called out of range Using an out of range index value does not always produce an error message by the compiler!!! It produces a WARNING, but the program will often give a run-time error So, DON T rely on the compiler catching your mistakes! Be Proactive! 5/8/18 Matni, CS16, Sp18 24

Out of Range Problems See demo files: basic_arrays.cpp Let s say we have the following: int a[6], i = 7; Then we execute the statement: a[i] = 238; This causes The computer to calculate the address of the illegal a[7] This address could be where some other variable in the program is stored! The value 238 will be stored at the address calculated for a[7] Congrats! You ve now messed with the integrity of computer memory! You could get run-time errors OR YOU MIGHT NOT!!! (unpredictable) This is bad practice! Keep track of your arrays! 5/8/18 Matni, CS16, Sp18 25

Default Values If too few values are listed in an initialization statement The listed values are used to initialize the first of the indexed variables The remaining indexed variables are initialized to a zero of the base type Example: int a[10] = {5, 5}; // Note array size given initializes a[0] and a[1] to 5 and a[2] through a[9] to 0 NOTE: This is called an extended initializer list and it only works in the latest versions of C++ compilers (version 11 or later). 5/8/18 Matni, CS16, Sp18 26

Range-Based For Loops C++11 (and later) includes a new type of for loop: The range-based for-loop simplifies iteration over every element in an array. For example, the following code outputs: 2 4 6 8 int arr[ ] = {2, 4, 6, 8}; for (int x : arr) { cout << x << ; } 5/8/18 Matni, CS16, Sp18 27

Arrays in Functions Indexed variables can be arguments to functions Example: If a program contains these declarations: void my_function(int x);... int i, n, a[10]; Variables a[0] through a[9] are of type int, so making these calls IS legal: my_function( a[0] ); my_function( a[3] ); my_function( a[i] ); BUT! This call is NOT legal: my_function( a[] ); or my_function( a ); 5/8/18 Matni, CS16, Sp18 28

Arrays as Function Arguments You can make an entire array a formal parameter for a function That is, as an input to a function But you cannot make an entire array the RETURNED value for a function That is, as an output from a function An array parameter behaves much like a call-by-reference parameter 5/8/18 Matni, CS16, Sp18 29

Passing an Array into a Function An array parameter is indicated using empty brackets in the parameter list such as void fill_up(int a[], int size); 5/8/18 Matni, CS16, Sp18 30

Function Calls With Arrays If function fill_up is declared in this way (note: uses [ ]!!!) void fill_up(int a[], int size); and array score is declared this way: int score[5], number_of_scores = 5; fill_up is called in this way (note: no [ ]!!!) fill_up(score, number_of_scores); Note that the array values can be changed by the function Even though it looks like it s being passed-by-value it s actually being passed-by-reference. We ll discuss this more with pointers another time 5/8/18 Matni, CS16, Sp18 31

5/8/18 Matni, CS16, Sp18 32

Array Argument Details Recall: What does the computer know about an array? The base type The address of the first indexed variable The number of indexed variables What does a function need know about an array argument? The base type The address of the first indexed variable 5/8/18 Matni, CS16, Sp18 33

Array Parameter Considerations Because a function does not know the size of an array argument The programmer should include a formal parameter that specifies the size of the array The function can process arrays of various sizes Example: function fill_up from on pg. 392 of the textbook can be used to fill an array of any size: fill_up(score, 5); fill_up(time, 10); 5/8/18 Matni, CS16, Sp18 34

But IS there a way to CALCULATE the Size of an Array? Yes, there is but not with regular arrays You will want to use dynamic arrays We ll talk about those later on with pointers For now, get used to the idea of passing the size of an array into a function that has the array as argument. 5/8/18 Matni, CS16, Sp18 35

const Modifier See demo files: array_function.cpp Array parameters allow a function to change the values stored in the array arg. Similar to how a parameter being passed by reference would be If you want a function to not change the values of the array argument, use the modifier const An array param. modified w/ const is called a constant array parameter Example: void show_the_world(const int a[ ], int size); If const is used to modify an array parameter: it has to be used in both the function declaration and definition 5/8/18 Matni, CS16, Sp18 36

Returning An Array Recall that functions can return a value of type int, double, char,, or even a class type (like string) BUT functions cannot return arrays We ll learn later how to return a pointer to an array instead 5/8/18 Matni, CS16, Sp18 37

q Begin Lab6 on Wednesday q Do HW10 by next Thursday YOUR TO-DOs q Visit Prof s and TAs office hours if you need help! q Practice all your skills 5/8/18 Matni, CS16, Sp18 38

5/8/18 Matni, CS16, Sp18 39