Presentation is loading. Please wait.

Presentation is loading. Please wait.

What is wrong in the following function definition

Similar presentations


Presentation on theme: "What is wrong in the following function definition"— Presentation transcript:

1 What is wrong in the following function definition
int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; }

2 What is wrong in the following function definition
int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }

3 What is the output of the following program
#include <iostream> using namespace std; int main() { int nums[4] = {30, 21, 45, 67}; change(nums, 4); for (int i=0; i<4; i++) cout << nums[i] << " " ; } void change(int nums[], int size) int *tmp_ptr = new int[size]; int i; for (i=0, i<size, i++) *tmp_ptr= nums[(i+1)%size]; cout << *(tmp_ptr++) << " "; cout << "\n";

4 What is the output of the following program
#include <iostream> using namespace std; int main() { int nums[4] = {30, 21, 45, 67}; change(nums, 4); for (int i=0; i<4; i++) cout << nums[i] << " " ; } void change(int nums[], int size) int *tmp_ptr = new int[size]; int i; for (i=0, i<size, i++) *tmp_ptr= nums[(i+1)%size]; cout << *(tmp_ptr++) << " "; cout << "\n";

5 What is the output of the following program
#include <iostream> using namespace std; void change(int nums[], int size); int main() { int nums[4] = {30, 21, 45, 67}; change(nums, 4); for (int i=0; i<4; i++) cout << nums[i] << " " ; } void change(int nums[], int size) int *tmp_ptr = new int[size]; int i; for (i=0; i<size; i++) *tmp_ptr= nums[(i+1)%size]; cout << *(tmp_ptr++) << " "; cout << "\n";

6 How about now? #include <iostream> using namespace std;
void change(int num[], int size); int main() { int nums[4] = {30, 21, 45, 67}; change(nums, 4); for (int i=0; i<4; i++) cout << nums[i] << " " ; } void change(int nums[], int size) int *tmp_ptr = nums; int i; int tmp_val = *tmp_ptr; for (i=0; i<size; i++) if (i<size-1) *tmp_ptr= nums[(i+1)]; else *tmp_ptr = tmp_val; cout << *(tmp_ptr++) << " "; cout << "\n";

7 What is the output of the following code?
#include <iostream> using namespace std; void increase(int, int &); int main() { int nums[2] = {30, 21}; increase (nums[0], nums[1]); cout << nums[0] << " " << nums[1]; } void increase(int num1, int &num2) num1 += num2;

8 What is the output of the following code?
#include <iostream> using namespace std; void increase(int &, int ); int main() { int nums[2] = {30, 21}; increase (nums[0], nums[1]); cout << nums[0] << " " << nums[1]; } void increase(int &num1, int num2) num1 += num2;

9 C++ I/O Streams

10 C++ I/O occurs in streams, which are sequences of bytes.
If bytes flow from a device like a keyboard, a disk drive, or a network connection etc. to main memory, this is called input operation (or input stream).  If bytes flow from main memory to a device like a display screen, a printer, a disk drive, or a network connection, etc, this is called output operation (or output stream). Typical header files <iostream> <fstream>

11 under <iostream>
The standard output stream (cout) The predefined object cout is an instance of ostream class. The cout object is said to be "connected to" the standard output device, which usually is the display screen. The cout is used in conjunction with the stream insertion operator, which is written as <<. The standard input stream (cin) The predefined object cin is an instance of istream class. The cin object is said to be attached to the standard input device, which usually is the keyboard. The cin is used in conjunction with the stream extraction operator, which is written as >> . string name; cout << "Please enter your name: "; cin >> name; cout << "Your name is: " << name << endl;

12 under <iostream>
The standard error stream (cerr) The predefined object cerr is an instance of ostream class. The cerr object is said to be attached to the standard error device, which is also a display screen but the object cerr is un-buffered and each stream insertion to cerr causes its output to appear immediately. The cerr is also used in conjunction with the stream insertion operator char str[] = "Unable to read...."; cerr << "Error message : " << str << endl; The standard log stream (clog) The predefined object clog is an instance of ostream class. The clog object is said to be attached to the standard error device, which is also a display screen but the object clog is buffered. This means that each insertion to clog could cause its output to be held in a buffer until the buffer is filled or until the buffer is flushed.

13 File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include but not limited to Various data analysis applications Data visualization Scientific computing Graphics and gaming Information management systems Log and run-time information saving in HPC …… Pretty much every major application

14 Files There are typically two types of files that a program will handle despite different formats. Text files: also be called ASCII files because the data they contain uses an ASCII encoding scheme. They are human readable and can be moved from one computer to another (same ASCII characters). Binary files: consist of a sequence of binary digits. They are designated to be read by programs, and NOT by human. They are typically more efficient (to load and store) than text files. But they could be machine dependent due to the different bytes for the same digits.

15 C++ File I/O Stream C++ provides the following classes to perform output and input of characters to/from files: ofstream: Stream class to write on files ifstream: Stream class to read from files fstream: Stream class to both read and write from/to files.

16 Let us focus on the text file…

17 A simple example of writing to an ASCII file
(i.e., program sends output) // write to an ASCII file #include <iostream> #include <fstream> using namespace std; int main () { ofstream myfile; myfile.open (“test.txt"); myfile << “I am writing to the file.\n"; myfile.close(); return 0; }

18 A simple example of writing to an ASCII file
(i.e., program sends output) // write to an ASCII file #include <iostream> #include <fstream> using namespace std; int main () { ofstream myfile; myfile.open (“test.txt"); myfile << “I am writing to the file.\n"; myfile.close(); return 0; } File I/O libraries

19 A simple example of writing to an ASCII file
// write to an ASCII file #include <iostream> #include <fstream> using namespace std; int main () { ofstream myfile; myfile.open (“test.txt"); myfile << “I am writing to the file.\n"; myfile.close(); return 0; } create an output stream object

20 A simple example of writing to an ASCII file
// write to an ASCII file #include <iostream> #include <fstream> using namespace std; int main () { ofstream myfile; myfile.open (“test.txt"); myfile << “I am writing to the file.\n"; myfile.close(); return 0; } Open a file using the output object (i.e., link the stream object to file)

21 A simple example of writing to an ASCII file
// write to an ASCII file #include <iostream> #include <fstream> using namespace std; int main () { ofstream myfile; myfile.open (“test.txt"); myfile << “I am writing to the file.\n"; myfile.close(); return 0; } Write to the file Start at beginning of file to end

22 A simple example of writing to an ASCII file
// write to an ASCII file #include <iostream> #include <fstream> using namespace std; int main () { ofstream myfile; myfile.open (“test.txt"); myfile << “I am writing to the file.\n"; myfile.close(); return 0; } Close the file which will push/flush what has been written to the buffer into the file in the physical space. Guess what may happen if the program crashes before the file is closed?

23 More about opening a file to write
An open file is represented within a program by a stream (i.e., an object of one of these classes; in the previous example, this was myfile) and any input or output operation performed on this stream object will be applied to the physical file associated to it. In order to open a file with a stream object we use its member function open: open (filename, mode); Where filename is a string representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags ios::in Open for input operations. ios::out Open for output operations. ios::binary Open in binary mode. ios::ate Set 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::app All output operations are performed at the end of the file, appending the content to the current content of the file. ios::trunc If the file is opened for output operations and it already existed, its previous content is deleted and replaced by the new one.

24 File Names Programs and files Files have two names to our programs
External file name Also called "physical file name" Like "infile.txt" Sometimes considered "real file name" Used only once in program (to open) Stream name Also called "logical file name" Program uses this name for all file activity

25 File Flush Output often "buffered"
Temporarily stored before written to file Written in "groups" Occasionally might need to force writing: outStream.flush(); Member function flush, for all output streams All buffered output is physically written Closing file automatically calls flush()

26 // writing on a text file
#include <iostream> #include <fstream> using namespace std; int main () { ofstream myfile (“test2.txt"); if (myfile.is_open()) { myfile << “First line.\n"; myfile << “Second line.\n"; myfile << “Third line.\n"; myfile.close(); } else cout << "Unable to open file"; return 0;

27 Declare the stream object and open the file at the same time
// writing on a text file #include <iostream> #include <fstream> using namespace std; int main () { ofstream myfile (“test2.txt"); if (myfile.is_open()) { myfile << “First line.\n"; myfile << “Second line.\n"; myfile << “Third line.\n"; myfile.close(); } else cout << "Unable to open file"; return 0; Declare the stream object and open the file at the same time Always a good habit to check whether the file is open successfully or not!

28 #include <iostream>
#include <fstream> using namespace std; //Declaration of the function that computes the average of the array float avg(float nums[], int size); int main() { float *nums; int size; cout << "Please input the size of the array: " ; cin >> size; if (size <=0 ) { //check the validity of the input integer cout << "Invalid size!"; exit(1); } nums = new float[size]; for (int i=0; i<size; i++) //accept user input of the numbers cin >> nums[i]; float avg_val = avg(nums, size); //call the function that computes the average ofstream outStream (“output.txt”); if (outStream.is_open()){ outStream << "The average of these numbers is " <<avg_val << “\n”; outStream.close(); delete [] nums; //Definition of the function that computes the average of the array float avg(float nums[], int size) float sum = 0.; for (int i=0; i<size; i++) sum += nums[i]; return (sum/size);

29 Read from an ASCII file Two important things need to handle when reading from a file!!

30 Read from an ASCII file Two important things need to handle when reading from a file!! The format of the file is needed!! The following two formats of the same data will need different ways to read 20.0, 34.4, 41.6, … We also need to know when we reach the end of the file !!

31 #include<iostream>
#include<fstream> using namespace std; int main() { ifstream inStream; inStream.open("text.txt"); char output[100]; if (inStream.is_open()) while (!inStream.eof()) { inStream >> output; cout << output; } //end of while } // end of if inStream.close(); return 0; }

32 checking the end of file Read from a text file
#include<iostream> #include<fstream> using namespace std; int main() { ifstream inStream; inStream.open("text.txt"); char output[100]; if (inStream.is_open()) while (!inStream.eof()) { inStream >> output; cout << output; } //end of while } // end of if myReadFile.close(); return 0; } checking the end of file Read from a text file output serves as a buffer

33 Character I/O with Files
All cin and cout character I/O same for files! Member functions work same: get, getline put, putback, peek, ignore

34 Reading information without using cin
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { string info; ifstream infile; infile.open (“students.txt"); while(!infile.eof()) // To get you all the lines. getline(infile, info); // Saves the line in info. cout << info; // Prints our info. } infile.close(); return 0; Reading information without using cin #include <iostream> #include <fstream> using namespace std; int main () { ifstream myStream("example.txt"); // open file char c; while (myStream.get(c)) // loop getting single characters cout << c; if (myStream.eof()) // check for EOF cout << "[EoF reached]\n"; myStream.close(); // close file return 0; }

35 Checking End of File Use loop to process file until end
Typical approach Two ways to test for end of file Member function eof() inStream.get(next); while (!inStream.eof()) { cout << next; inStream.get(next); } Reads each character until file ends eof() member function returns bool

36 End of File Check with Read
Second method read operation returns bool value! (inStream >> next) Expression returns true if read successful Returns false if attempt to read beyond end of file In action: double next, sum = 0; while (inStream >> next) sum = sum + next; cout << "the sum is " << sum << endl;

37 End of File Check with Read
Second method read operation returns bool value! (inStream >> next) Expression returns true if read successful Returns false if attempt to read beyond end of file In action: double next, sum = 0; while (inStream >> next) sum = sum + next; cout << "the sum is " << sum << endl;

38 How to read data files with either of the following formats?
20.0, 34.4, 41.6, … #include <iostream> #include <fstream> using namespace std; int main () { ifstream myStream(“data.txt"); // open file int c; if (!myStream.is_open()) { cout << “Cannot open the file!\n”; exit(1); } while (!myStream.eof()) // check for EOF // How to read?? cout << c << “ “; myStream.close(); // close file return 0;

39 How to read data files with either of the following formats?
20.0, 34.4, 41.6, … #include <iostream> #include <fstream> using namespace std; int main () { ifstream myStream(“data.txt"); // open file int c; if (!myStream.is_open()) { cout << “Cannot open the file!\n”; exit(1); } while (!myStream.eof()) // check for EOF myStream >> c; cout << c << “ “; myStream.close(); // close file return 0;

40 How to read data files with either of the following formats?
20.0, 34.4, 41.6, … #include <iostream> #include <fstream> using namespace std; int main () { ifstream myStream(“data.txt"); // open file int c; char ch; if (!myStream.is_open()) { cout << “Cannot open the file!\n”; exit(1); } while (!myStream.eof()) // check for EOF myStream >> c >> ch; cout << c << “ “; myStream.close(); // close file return 0;

41 File Names as Input Stream open operation
Argument to open() is string type Can be literal (used so far) or variable char fileName[16]; ifstream inStream; cout << "Enter file name: "; cin >> fileName; inStream.open(fileName); Provides more flexibility

42 Random Access to Files Sequential Access Random Access
Most commonly used (as we have seen!) Random Access Rapid access to records Perhaps very large database Access "randomly" to any part of file Use fstream objects input and output

43 Random Access Tools Opens same as istream or ostream
Adds second argument fstream rwStream; rwStream.open("stuff", ios::in | ios:: out); Opens with read and write capability Move about in file rwStream.seekp(1000); Positions put-pointer at 1000th byte (for writing to) rwStream.seekg(1000); Positions get-pointer at 1000th byte (for reading from)

44 Random Access Sizes To move about  must know sizes
sizeof() operator determines number of bytes required for an object: sizeof(s) //Where s is string s = "Hello" sizeof(10) sizeof(double) sizeof(myObject) Position put-pointer at 100th record of objects: rwStream.seekp(100*sizeof(myObject) – 1);

45 Formatting Output with Stream Functions
cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); Outputs numbers in "money" form (12.52) Can use on any output stream File streams have same member functions as cout object

46 Output Member Functions
Consider: outStream.setf(ios::fixed); outStream.setf(ios::showpoint); outStream.precision(2); Member function precision(x) Decimals written with "x" digits after decimal Member function setf() Allows multitude of output flags to be set

47 More Output Member Functions
Consider: outStream.width(5); Member function width(x) Sets width to "x" for outputted value Only affects "next" value outputted Must set width before each value in order to affect all Typical to have "varying" widths To form "columns"

48 Flags Recall: member function setf()
Sets condition of output flags All output streams have setf() member Flags are constants in class ios In library <iostream>, std namespace

49 setf() Examples Common flag constants:
outStream.setf(ios::fixed); Sets fixed-point notation (decimal) outStream.setf(ios::showPoint) Always include decimal point outStream.setf(ios::right); Sets right-justification Set multiple flags with one call: outStream.setf(ios::fixed | ios::showpoint | ios::right);

50 Manipulators Manipulator defined: "A function called in nontraditional way" Can have arguments Placed after insertion operator Do same things as member functions! In different way Common to use both "together" setw() and setprecision() are in library <iomanip>, std namespace

51 Manipulator Example: setw()
setw() manipulator: cout << "Start" << setw(4) << << setw(4) << 20 << setw(6) << 30; Results in: Start Note: setw() affects only NEXT outputted value Must include setw() manipulator before each outputted item to affect all

52 Manipulator setprecision()
setprecision() manipulator: cout.setf(ios::fixed | ios::showpoint); cout << "$" << setprecision(2) << 10.3 << " " << "$" << 20.5 << endl; Results in: $ $20.50


Download ppt "What is wrong in the following function definition"

Similar presentations


Ads by Google