1 one-dimensional arrays and functions passing one-dimensional arrays to functions –in the call...

52
1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions In the call statement, using the name of an array without bracket [ ] passes the address of the array to the function The called function uses the calling function’s array data Sending an array to a function “appears” to be sending a copy of the array to the function A function that uses array must indicate the array data type in the prototype and function header line

Upload: jade-donna-merritt

Post on 19-Jan-2016

248 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

1

One-Dimensional Arrays and Functions

• Passing one-dimensional arrays to functions– In the call statement, using the name of an

array without bracket [ ] passes the address of the array to the function

– The called function uses the calling function’s array data

– Sending an array to a function “appears” to be sending a copy of the array to the function

– A function that uses array must indicate the array data type in the prototype and function header line

Page 2: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

2

One-Dimensional Arrays and Functions

Comparing Single Variables and One-Dimensional Arrays in Functions Single Float Value Function Function with a One-Dimensional Array

//Prototype //Prototype

void Function1 (float) void Function2 (float []);

int main() int main()

{ {

float x; float q[100];

Function1(x); Function2(q);

return 0; return 0;

} }

void Function1(float x) void Function2(float q[])//See Note 1

{ {

//function has its own //function actually uses main’s

//copy of x //array

//body of function //body of function

} }

Note 1: The address is passed to the function, and main’s array data is

accessed from the function. Also, for one-dimensional arrays, the size

of the array is not needed in the prototype and function header line.

注意此例 Function2宣告輸入變數的方式

Page 3: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

3

Illustrating Function2 OperationsPassing Arrays to Functions

Page 4: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

4

One-Dimensional Arrays and Functions

• Array Averaging Program//Program Average Value of 1D Array#include <iostream.h>

float Ave1D(float [], int); //prototype passing array to thisint main(){

float x[100], average,num = 1000.0;int i, total = 100;

//we'll fill x with values 1000 - 1100for (i = 0; i < 100; ++ i){

x[i] = num;num++; // num starts at 1000, incr each time

}average = Ave1D( x , total);cout << "\n The average value of the array is " << average << endl;return 0;

}

float Ave1D(float temp[], int total){

int i;float sum = 0.0, ave;for(i = 0; i < total; ++i)

sum = sum + temp[i];ave = sum/total;return ave;

}

Page 5: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

5

temp 實為一 pointer

Page 6: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

6

One-Dimensional Arrays and Functions

//Program: Gimme Five Numbers-Second Attempt// Declare the array in the calling function.#include <iostream.h>

void Gimme5Numbers(int [] ); //prototype passes an array to the function

int main(){

int five_nums[5], i;

cout << "\n Welcome to Gimme5Numbers Program \n\n";Gimme5Numbers( five_nums );cout << "\n The 5 values in the five_nums array are: \n";for(i = 0; i < 5; ++i)

cout << "Element # " << i << " = " << five_nums[i] << endl;return 0;

}

void Gimme5Numbers( int five_nums[] ){

int i;for(i = 0; i < 5; ++i) {

cout << "\n Enter Number " << i+1 << "==> ";cin >> five_nums[i];

}} //No return statement is required here

Page 7: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

7

Page 8: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

8

Character Strings

• Text data are typically maintained as one-dimensional character arrays– These arrays are known as character strings– Syntax

char variable_name[size];

– Null-terminated, i.e., the array has the null character ‘\0’ at the end of the character data

• Null character indicates the end of the text data

– The string must contain a null character• Always use a size value large enough to include

this extra character

Page 9: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

9

Page 10: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

10

Character Strings

• Null Character– Always ensure that the character string has

been null-terminated• C++ uses the null character ‘\0’ to indicate where

the end of the text data is

– Otherwise, functions provided in the string library and output functions in iostream may work incorrectly

Page 11: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

11

Character Strings

• Null Character ( 續 )– Consider the following code

#include <iostream.h>void main(){

char str[15]={‘H’,’O’,’W’,’D’,’Y’,’ ‘,’P’,’A’,’L’}; char line[15] = “I love C++!”; cout << str <<endl; cout << line;

}

– Now use the assignment statement without putting the null character#include <iostream.h>void main(){

char new_str[15]; new_str[0]=‘H’; new_str[1]=‘O’; new_str[2]=‘W’; new_str[3]=‘D’; new_str[4]=‘Y’; cout << new_str <<endl;

}

Page 12: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

12

str and line Character Strings After Initialization

new_str after Assignment

Page 13: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

13

Character Strings

• Null Character ( 續 )– Without the null character, the computer cannot

determine where the end of the string is located– To correct, in the last code, add

new_str[5] = ‘\0’;

Page 14: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

14

Character Strings

• Character String Input

Terminology for Reading Character Data Term Definition extract To pull a character out of the stream and put in into a variable max Max number of characters to read into a variable delimiter A special character used by the programmer to tell the program when

to stop reading characters. If you select an x as the delimiter, the delimiter function will read characters until it sees an x. The function then stops reading the characters for that specific variable

new-line ‘\ n’ or the Enter Key

Page 15: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

15

Character Strings

• Character String Input ( 續 )– get(ch)

• Extract one character from the stream and place it into the variable named ch

• 例 char one; cin.get(one);

– get(string,max)• Extract characters from the stream and place them

into variable string until either max-1 characters have been read, a newline is found or an end of file is reached

• The string is null-terminated• If the newline is found, it is not extracted and

remains in the input stream until the next read operation

• 例 char name[30];cin.get(name,30);

Page 16: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

16

Character Strings

• Character String Input ( 續 )– get(string,max,delimiter)

• Extract characters from the stream and place them into variable string until either max-1 characters have been read, the delimiter character has been found, or an end of file is reached

• The string is null-terminated• The delimiter character is left in the input stream

until the next read operation• 例 char name[30];

cin.get(name,30,’x’);

Page 17: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

17

Character Strings

• Character String Input ( 續 )– getline(string,max) //c.f. get(string,max)

• Extract characters from the stream and place them into variable string until either max-1 characters have been read, a newline is found, or an end of file is reached

• The string is null-terminated• If the newline is found, it is extracted from the

stream but not put into the string• 例 char name[30];

cin.getline(name,30);

Page 18: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

18

Character Strings

• Character String Input ( 續 )– getline(string,max,delimiter)

• Extract characters from the stream and place them into variable string until either max-1 characters have been read, the delimiter character has been found, or an end of file is reached

• The string is null-terminated• If the delimiter character has been found, it is

extracted from the stream and not put in the string

• 例 char name[30];cin.getline(name,30,’x’);

Page 19: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

19

Character Strings

• Character String Input ( 續 )– The standard cin function reads character data

until it sees a whitespace character• At this point, cin stops reading and places a null

character in the string

– The get function leaves a newline or the delimiter in the input stream

– The getline function removes the newline or delimiter character from the input stream

• Using getline is preferable when reading character data from the keyboard or file

Page 20: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

20

Character Strings

//Program: Who Do You Love?//Using cin.getline and cin to read character strings.#include <iostream.h>int main(){ char text1[15], text2[15] ; cout << "\n Using getline(text1,14) Enter ==> I love C++! "; cin.getline(text1,14);

cout << "\n Using cin >> text2 Enter ==> I love C++! "; cin >> text2;

cout << "\n Text1 = " << text1 ; cout << "\n Text2 = " << text2 << endl; return 0;}

Page 21: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

21

! \0

Page 22: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

22

Character Strings

//Program: Who Do You Love? Part Two//We will use three different ways to read a phrase.//1. cin.getline with a delimiter//2. cin //3. cin.getline //We use a cin.ignore to flush the enter key from the input queue

#include <iostream.h>int main(){

char text1[15], text2[15], text3[15];

cout << "\n Who Do You Love? Part Two \n";

cout << "\n Using getline(text1,14,'C') Enter ==> I love C++! ";cin.getline(text1, 14, 'C');cin.ignore(20,'\n');cout << " Output Text1 ==> " << text1;

cout << "\n\n Using cin >> text2 Enter ==> I love C++! ";cin >> text2;cin.ignore(20,'\n');cout << " Output Text2 ==> " << text2;

cout << "\n\n Using getline(text3,14) Enter==> I love C++! ";cin.getline(text3, 14);cout << " Output Text3 ==> " << text3;

cout << "\n\n\n Don't you love C++?" << endl;return 0;

}

Page 23: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

23

Program Output

Page 24: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

24

Page 25: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

25

Character Strings: cin.ignore 的用法

Page 26: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

26

Reading Both Numeric and Character Data//Program 6-8 Broken PROBLEM PROGRAM DOES NOT WORK CORRECTLY

//Using cin.getline and cin to read user information.#include <iostream.h>int main(){

char name[20], football_team[25];int age, num_kids;

// ask user for name, age, football team and number of kidscout<< "\n Enter your name: ";cin.getline(name,20);cout << "\n Enter your age: ";cin >> age;cout << "\n What is your favorite football team? ";cin.getline(football_team,24);cout << "\n How many kids do you have? ";cin >> num_kids;

// write info out to screencout << endl << name << ", your team is " << football_team << "\nYou are " << age << " years old and have " << num_kids << " kids." << endl;

return 0;}

Page 27: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

27

Reading Both Numeric and Character Data

• The above program contains pitfalls– When the program runs, we can enter the user’s

name and age. However, the program does not wait for the input of football_team, but stops for the user to enter num_kids

– Why?• cin does not remove the Enter key from the input

stream

Page 28: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

28

Reading Both Numeric and Character Data

• Two ways to work around– Approach 1: Use cin.ignore to flush the

extraneous characters in the stream• Foregoing code can be changed// ask user for name, age, football team … cout<< "\n Enter your name: ";cin.getline(name,20);cout << "\n Enter your age: ";cin >> age;cin.ignore(10,’\n’);cout << "\n What is your favorite football team? ";cin.getline(football_team,24);

Page 29: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

29

Reading Both Numeric and Character Data

• Two ways to work around ( 續 )– Approach 2: Use a get function to read a single

character out of the stream. 修改 Program 6-8 如下

char junk;// ask user for name, age, football team … cout<< "\n Enter your name: ";cin.getline(name,20);cout << "\n Enter your age: ";cin >> age;cin.get(junk); // pull out the Enter keycout << "\n What is your favorite football team? ";cin.getline(football_team,24);cout << “\n How many kids do you have? “;cin >> num_kids;cin.get(junk);

Page 30: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

30

Reading Both Numeric and Character Data

• Caution!– A program may become stuck if the user enters

non-numeric data when cin is expecting a number

• Preferred approach– Use a getline for reading numeric values

• Reading the numeric value into a character string

– Along with functions• atoi converts ASCII characters to integers• atol converts ASCII characters to a long integer• atof converts a string to a double or floating

point value

– (Next slides gives an example)

Page 31: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

31

Reading Both Numeric and Character Data//Program 6-9 Using cin.getline to read integer and character strings.#include <iostream.h>#include <stdlib.h> //used for atoi function

int main(){

char name[20], football_team[25];int age, num_kids;char temp[10];

// ask user for name, age, football team and number of kidscout<< "\n Enter your name: ";cin.getline(name,20);cout << "\n Enter your age: ";cin.getline(temp,10);age = atoi(temp);cout << "\n What is your favorite football team? ";cin.getline(football_team,25);cout << "\n How many kids do you have? ";cin.getline(temp,10);num_kids = atoi(temp);// write info out to screencout << endl << name << ", your team is " << football_team << "\nYou are " << age << " years old and have " << num_kids << " kids." << endl;return 0;

}

Page 32: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

32

Character String Functions in C++

Functions in string.h

Page 33: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

33

Functions in string.h (cont’d)

Page 34: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

34

Remarks

• strcmp(s1,s2) can be used to determine the alphabetic order between s1 and s2– strcmp(“Apples”,”Bananas”) < 0

Page 35: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

35

String to Numeric Functions

Page 36: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

36

Numeric to String Functions

• #include <stdlib.h>• itoa ( 數值 , 字串 , 基底 ) // 整數轉成字串

• 範例char intArray[10];

itoa(1234, intArray, 8); //1234 轉成字串 "2322"itoa(1234, intArray, 10); //1234 轉成字串 "1234"itoa(1234, intArray, 16); //1234 轉成字串 "4d2"

Page 37: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

37

itoa【函式原型】 char *itoa( int value, char *string, int radix );【表 頭 檔】 <stdlib.h>【功  能】將整數 value 以 radix 為基底,轉換成字串string

ltoa

【函式原型】 char *ltoa( long value, char *string, int radix );【表 頭 檔】 <stdlib.h>【功  能】將長整數 value 以 radix 為基底,轉換成字串 string

常用資料轉換函式 (1/3)

Page 38: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

38

ultoa

【函式原型】 char *ultoa(unsigned long value, char *string, int radix);【表 頭 檔】 <stdlib.h>【功  能】將無符長整數 value 以 radix 為基底,轉換成字串string 。(在 Dev-C++ 中以 _ultoa 代替 ultoa )

toascii

【函式原型】 int toascii( int c );【表 頭 檔】 <ctype.h>【功  能】將字元 c 轉換成 ASCII 碼。

常用資料轉換函式 (2/3)

Page 39: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

39

tolower

【函式原型】 int tolower( int c );【表 頭 檔】 <stdlib.h> 或 <ctype.h>【功  能】將字元 c 轉換為小寫的 ASCII 碼。

toupper

【函式原型】 int toupper( int c );【表 頭 檔】 <stdlib.h> 或 <ctype.h>【功  能】將字元 c 轉換為大寫的 ASCII 碼

常用資料轉換函式 (3/3)

Page 40: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

40

例:二進位數轉換為十進位數 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int main() { char bin[30]; int len, i, sum = 0; char ch[2] = {'\0','\0‘}; cout << "請輸入一個二進位的數: "; cin >> bin; len=strlen(bin); for (i = 0; i < len; i++) { ch[0] = bin[i]; sum += atoi(ch)*(int)pow(2,len-i-1); // sum += (bin[i]-‘0’)*(int)pow(2,len-i-1); } cout << "轉為十進位 = “ << sum; return 0; }

Page 41: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

41

Multidimensional Arrays and Functions

• Multidimensional arrays require that all but the beginning array size be specified in the prototype and function header line– 例: If a 3-dimensional array is passed to a

function, necessary statements are:

void MyFunc (float [][3][7]);//function prototype includes size

float m[2][3][7]; //array declaration

MyFunc (m); //call uses the array name

void MyFunc (float m[][3][7]) //function header line has

sizes

Page 42: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

42//Program Utility Costs with Miraculous Input#include <iostream.h>float Totals(float [][3], float *, float *, float *);void main(){

float util_costs[12][3];float total_cost, phone, water, elec;

/* Data input here: . . . */total_cost = Totals(util_costs, &elec, &phone, &water);cout << "\n The Total Utility Cost per year: " << total_cost << "\n Electric = " << elec << "Phone = " << phone << "Water = " << water;

}

float Totals(float ut[][3], float *ptr0, float *ptr1, float *ptr2){

float sum = 0.0;for (int col = 0; col < 3; ++col){

for (int row = 0; row < 12; ++row)sum += ut[row][col];

if (col == 0)*ptr1 = sum;

else if (col == 1)*ptr0 = sum;

else *ptr2 = sum;sum = 0.0;

}return (*ptr0 + *ptr1 + *ptr2);

}

Page 43: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

43

Another Program: Snow White//Program 6-10 Snow White and Character String Array

#include <iostream.h>void WriteNames( char [][15]); //prototype

int main(){

// Declare and initialize the arraychar dwarfs[7][15] = {"Doc", "Sleepy", "Dopey", "Grumpy",

"Sneezy", "Bashful", "Happy" };

WriteNames(dwarfs);return 0;

}

void WriteNames(char dwarfs[][15]){

int i;for (i = 0; i < 7; ++i) {

cout << "Dwarf # " << i+1 << " is " << dwarfs[i] << endl;}

}

Page 44: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

44

Array out of Bounds

Cannot tell what part of the computer memory has been written overby the program or what damage has been done!!Cannot tell what part of the computer memory has been written overby the program or what damage has been done!!

Page 45: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

45

Array out of Bounds = Big Trouble

• An out-of-bounds array can wreak havoc ( 造成嚴重的破壞 ) on your computer system when the program is executed– Computer crash or locked, system rebooted, …– Innocent bystanders ( 旁觀者 ) (data variables)

are likely to become victims of illegal operations• Illegal array activity usually alter other variable

values

• Deterrent ( 遏制 )– Programmer keeps a close eye on the array

indices– Make sure that your strings large enough for

your data and the null character

Page 46: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

46

Filling Arrays from Data Files

• In practice, data are usually read from a data file into array, or vice versa– File open/close– (See the following example)

Page 47: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

47

/* Program: Favorite Word Read in a word and a phrase and determine if the word is in the phrase. Also report length of word and phrase. */#include <iostream.h>#include <string.h>bool FindFavorite(char [], char []);

void main( ){

char phrase[80],word[15], answer[5];do { cout << "\n Please enter your FAVORITE word ===> "; cin.getline(word,15); cout << "\n\n Please type in a sentence or a phrase.\n\n==> "; cin.getline(phrase,80); if (FindFavorite(phrase,word) == true)

cout << "\n I see it! I see ==> " << word << " <== :-) \n"; else

cout << "\n I don't see ==> " << word << " <== :-(\n"; cout << "\n\n Do it again? Enter yes or no ==> "; cin.getline(answer,5);}while(strcmp(answer,"yes")== 0); //strcmp returns 0 if strings matchcout << "\n\n Aren't strings wonderful?\n\n";

}

bool FindFavorite(char phrase[], char word[]){

bool result;char* IsItThere; //declare a character pointer for strstrIsItThere = strstr(phrase,word);result = (IsItThere == NULL)? false: true; return (result);

}

Filling Arrays from Data Files

Page 48: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

48

Practice: Weather, Data File I/O

Page 49: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

49

Practice: Weather, Data File I/O (1/2)//Program 6-12 Weather, Arrays, Data File I/O#include <iostream.h>#include <fstream.h> //required for file I/O#include <stdlib.h> //required for exit()

#define FILE_IN "weather.txt" //place the data file in the project file#define FILE_OUT "report.out"

float FindAve(float[], int);void HighLow(float[], float[], float*, float*, int);

int main(){

float high[31],low[31], high_ave, low_ave, hottest, coldest;char date[25],location[50];int total_days, i=0;//first must set up streams for input and outputifstream input; //setup input stream objectofstream output; //setup output stream object//open for input and don't create if it is not there input.open(FILE_IN, ios::in); if(!input) //check whether the input file is opened{

cout << "\n Can't find input file " << FILE_IN;exit(1);

}output.open(FILE_OUT, ios::out); //now open outputinput.getline(date,24); //read the first 2 lines into stringsinput.getline(location,49);while(!input.eof())//read until we reach the end of file{

input >> high[i] >> low[i];++i;

}

Page 50: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

50

total_days = i; // value is i 1 larger than total # of days read incout << "\n All Done Reading! "<<endl;high_ave = FindAve(high, total_days);low_ave = FindAve(low, total_days);HighLow(high, low, &hottest, &coldest, total_days);//now write date to output fileoutput << "Monthly Weather Report\n\nLocation: " << location

<< "\n Date: " << date << "\n\nAverage Temperatures: High " << high_ave << " Low " << low_ave << "\n\nHottest Temperature: " << hottest << "\nColdest Temperature: " << coldest;

input.close();output.close();return 0;

}

float FindAve(float x[], int total){

float sum = 0.0;for(int i = 0; i < total; ++i)

sum = sum + x[i];return(sum/total);

}

void HighLow(float high[], float low[], float *h_ptr, float *l_ptr, int total){

float hottest = high[0], coldest = low[0];for(int i = 0; i < total; ++i){

if(high[i] > hottest) hottest = high[i]; //*h_ptr = high[i];if(low[i] < coldest) coldest = low[i]; //*l_ptr = low[i];

}*h_ptr = hottest; *l_ptr = coldest;

}

Practice: Weather, Data File I/O (2/2)

Page 51: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

Flags for Opening a File

51

ios::in Open for input operations.

ios::out Open for output operations.

ios::binary

Open in binary mode.

ios::ateSet the initial position at the end of the file. If this flag is not set, the initial position is the beginning of the file.

ios::appAll output operations are performed at the end of the file, appending the content to the current content of the file.

ios::truncIf the file is opened for output operations and it already existed, its previous content is deleted and replaced by the new one.

• 例:– To open the file example.bin in binary mode to

add data, perform the following:ofstream myfile;myfile.open ("example.bin", ios::out | ios::app |

ios::binary);

Page 52: 1 One-Dimensional Arrays and Functions Passing one-dimensional arrays to functions –In the call statement, using the name of an array without bracket [

• “c:\\Weather.txt”• TED 講稿文字

52