CSC 221: Computer Programming I Fall 2001  file input  ifstream  open, >>, close  end-of-file  file output  ofstream  open, <<, close  input with.

Slides:



Advertisements
Similar presentations
1 Arrays and Strings Chapter 9 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
Advertisements

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 8- 1 Overview 8.1 An Array Type for Strings 8.2 The Standard string.
1 CSC 222: Computer Programming II Spring 2004  vectors  library, templated  advantages over arrays:  const-reference parameters  growable vectors.
CS 1620 File I/O. So far this semester all input has been from keyboard all output has been to computer screen these are just two examples of where to.
Chapter 10.
Computer Science 1620 Loops.
1 CIS 205 Practice Test George Lamperti A word that has a predefined meaning in a C++ program and cannot be used as a variable name is known as.
1 11/3/08CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
Computer Science 1620 Variables and Memory. Review Examples: write a program that calculates and displays the average of the numbers 45, 69, and 106.
Chapter 5: Loops and Files.
1 10/29/07CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
Computer Science 1620 Programming & Problem Solving.
1 Chapter 6 Looping Dale/Weems/Headington. 2 l Physical order vs. logical order l A loop is a repetition control structure based on a condition. l it.
Computer Science 1620 Arrays. Problem: Given a list of 5 student grades, adjust the grades so that the average is 70%. Program design: 1. read in the.
CS 1 Lesson 5 Loops and Files CS 1 -- John Cole.
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
What is the out put #include using namespace std; void main() { int i; for(i=1;i
Program Input and the Software Design Process ROBERT REAVES.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
11 Introduction to Object Oriented Programming (Continued) Cats II.
1 CSC 222: Computer Programming II Spring 2004 Searching and efficiency  sequential search  big-Oh, rate-of-growth  binary search Class design  templated.
Chapter 6 Looping.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
C++ Arrays. Agenda What is an array? What is an array? Declaring C++ arrays Declaring C++ arrays Initializing one-dimensional arrays Initializing one-dimensional.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 4: Continuing with C++ I/O Basics.
CSC 221: Computer Programming I Fall 2001  top-down design  approach to problem solving, program design  focus on tasks, subtasks, …  reference parameters.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
File I/O ifstreams and ofstreams Sections 11.1 &
1 CS161 Introduction to Computer Science Topic #13.
File Input and Output in C++. Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) Keyboard Screen executing program input data.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
1 Looping. 2 Chapter 6 Topics  While Statement Syntax  Phases of Loop Execution  Two Types of Loops: Count-Controlled Loops &Event-Controlled Loops.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
Disk Files for I/O your variable (of type ifstream) your variable (of type ofstream) disk file “myInfile.dat” disk file “myOut.dat” executing program input.
1 Cannon_Chapter9 Strings and the string Class. 2 Overview  Standards for Strings  String Declarations and Assignment  I/O with string Variables 
GE 211 Dr. Ahmed Telba. // compound assignment operators #include using namespace std; int main () { a =5 int a, b=3; a = b; a+=2; // equivalent to a=a+2.
Vectors One-Dimensional Containers. Problem A file contains a sequence of names and scores: Ann92 Bob84 Chris89... Using OCD, design and implement a program.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
1 09/27/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
Copyright © 2002 W. A. Tucker1 Chapter 9 Lecture Notes Bill Tucker Austin Community College COSC 1315.
Loops and Files. 5.1 The Increment and Decrement Operators.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
Looping ROBERT REVAES. Logical Operators  && AND  Both have to be true for it to evaluate to be true.  || OR  One or the other has to be true for.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
1 CSC 221: Computer Programming I Fall 2005 simple conditionals and expressions  if statements, if-else  increment/decrement, arithmetic assignments.
Input/Output. Objectives In this chapter you will: Learn what a stream is and examine input and output streams Explore how to use the input stream functions.
CSC 221: Computer Programming I Fall 2001  arrays  homogeneous collection of items, accessible via an index  initializing/traversing/displaying arrays.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 6 I/O Streams as an Introduction to Objects and Classes.
CS162 External Data Files 1 Today in CS162 External Files What is an external file? How do we save data in a file?
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Today’s Lecture  I/O Streams  Console I/O  File I/O  Tools for File I/O  Sequential.
File I/O in C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
ifstreams and ofstreams
New Structure Recall “average.cpp” program
Copyright © 2003 Pearson Education, Inc.
Today’s Lecture I/O Streams Tools for File I/O
Chapter 3 Input output.
CSC 143 Stream I/O Classes and Files [A11-A15, A38-A50]
CS150 Introduction to Computer Science 1
CS150 Introduction to Computer Science 1
Reading from and Writing to Files
ifstreams and ofstreams
Lecture 3 More on Flow Control, More on Functions,
Reading from and Writing to Files
Presentation transcript:

CSC 221: Computer Programming I Fall 2001  file input  ifstream  open, >>, close  end-of-file  file output  ofstream  open, <<, close  input with whitespace  get, getline

arrays recap important points:  arrays provide capability for storing related values in a single entity  can access individual values using an index  can traverse through the indices, systematically access all values in the array  can pass the entire array as a single parameter  for efficiency reasons, arrays are treated as pointers (references) to memory arrays make it possible to store and access large amounts of data  requiring the user to enter lots of data by hand is tedious each execution of the program requires re-entering the data  better solution: store the data in a separate file, read directly from the file requires only one entry by the user, can re-read as many times as desired

file input to read from a file, must declare an input file stream  similar to the standard input stream, only input comes from a file  in particular, can read values using >>  defined in the library #include // loads definition of the input // file stream class (ifstream)... ifstream myin;// declares input file stream myin.open("nums.dat");// opens the input file stream // using the file "nums.dat" int numbers[100]; for (int i = 0; i < 100; i++) {// reads numbers from the input myin >> numbers[i];// file stream & stores in array } myin.close();// closes the input file stream

averaging grades // avg.cpp // // Averages the numbers from a file. //////////////////////////////////////////////////// #include using namespace std; int main() { ifstream myin; myin.open("grades.dat"); int numGrades = 0, gradeSum = 0; int grade; myin >> grade; while (grade != -1) { gradeSum += grade; numGrades++; myin >> grade; } if (numGrades > 0) { double avg = (double)gradeSum/numGrades; cout << "Your average is " << avg << endl; } else { cout << "There are no grades!" << endl; } myin.close(); return 0; } suppose we wanted to store grades in a file to compute average, don't need to store the grades in an array – just read and process OPEN INPUT FILE STREAM; INITIALIZE GRADE COUNTER, SUM; READ FIRST GRADE; while (GRADE IS NOT SENTINEL){ ADD GRADE TO SUM; INCREMENT GRADE COUNTER; READ NEXT GRADE; } COMPUTE & DISPLAY AVERAGE

storing grades but suppose we wanted to allow the user to selectively display or manipulate the grades e.g., want to allow the user to specify a cutoff grade, then determine the # above the cutoff  must store in an array pseudo-code: OPEN INPUT FILE STREAM; READ GRADES & STORE IN ARRAY; PROMPT USER FOR CUTOFF; TRAVERSE ARRAY & COUNT; note: when you declare an array, must specify a maximum size in this case, don't know how many grades there will be as a result, must guess a maximum size and hope it's big enough

#include using namespace std; const int MAX_GRADES = 100; void ReadGrades(int grades[], int & numGrades); int CountAbove(const int grades[], int numGrades, int cutoff); int main() { int grades[MAX_GRADES], numGrades; ReadGrades(grades, numGrades); int cutoff; cout << "Enter the desired grade cutoff: "; cin >> cutoff; cout << "There are " << CountAbove(grades, numGrades, cutoff) << " grades above " << cutoff << endl; return 0; } ////////////////////////////////////////////// void ReadGrades(int grades[], int & numGrades) // Results: reads grades and stores in array // numGrades is set to the # of grades { ifstream myin; myin.open("grades.dat"); numGrades = 0; int grade; myin >> grade; while (grade != -1) { grades[numGrades] = grade; numGrades++; myin >> grade; } myin.close(); } int CountAbove(const int grades[], int numGrades, int cutoff) // Assumes: grades contains numGrades grades // Returns: number of grades >= cutoff { int numAbove = 0; for(int i = 0; i < numGrades; i++) { if (grades[i] >= cutoff) { numAbove++; } return numAbove; } cutoff display

Improvement 1: end-of-file a sentinel value is really not necessary for a file  the physical end-of-file marks the end of input input via >> evaluates to a Boolean value  if the input succeeds (the expected type of input is read in), the expression evaluates to true  if the input fails (the wrong type of input is read in or end-of-file has been reached), the expression evaluates to false thus, can have a while loop driven by an input statement void ReadGrades(int grades[], int & numGrades) // Results: reads grades and stores in array // numGrades is set to the # of grades { ifstream myin; myin.open("grades.dat"); numGrades = 0; int grade; while (myin >> grade) { grades[numGrades] = grade; numGrades++; } myin.close(); }

Improvement 2: guarding against OOB what if you guessed wrong when setting the size of the array?  suppose the user enters 101 grades  what will happen? must stop the loop before indexing out-of-bounds void ReadGrades(int grades[], int & numGrades) // Results: reads grades and stores in array // numGrades is set to the # of grades { ifstream myin; myin.open("grades.dat"); numGrades = 0; int grade; while (numGrades > grade) { grades[numGrades] = grade; numGrades++; } myin.close(); }

Improvement 3: generalizing file names we can generalize the program to read from an arbitrary file  can prompt the user for the file name, read into a string  note that the constructor for an ifstream requires a C-style string as argument (char array), not a C++ string object  fortunately, there is a string member function that automatically converts a C++ string to a C-style string void ReadGrades(int grades[], int & numGrades) // Results: reads grades and stores in array // numGrades is set to the # of grades { string filename; cout << "Enter the grades file name: "; cin >> filename; ifstream myin; myin.open( filename.c_str() ); numGrades = 0; int grade; while (numGrades > grade) { grades[numGrades] = grade; numGrades++; } myin.close(); }

Improvement 4: guarding against file errors we can test the ifstream to be sure that the specified file was opened correctly  the ifstream has a Boolean value associated with it  if the file exists (and not past end-of-file), the ifstream evaluates to true  otherwise, the ifstream evaluates to false  must clear the input file stream between attempts to open (in order to reset true/false value) void ReadGrades(int grades[], int & numGrades) // Results: reads grades and stores in array // numGrades is set to the # of grades { string filename; cout << "Enter the grades file name: "; cin >> filename; ifstream myin; myin.open( filename.c_str() ); while (!myin) { cout << "File not found. Try again: "; cin >> filename; myin.clear(); myin.open( filename.c_str() ); } numGrades = 0; int grade; while (numGrades > grade) { grades[numGrades] = grade; numGrades++; } myin.close(); }

in-class exercise suppose you have been hired by the Weather Channel  temperatures are automatically read at 5 minute intervals  temperature readings are stored in a file (in order, with midnight first)  at any given point in the day, you want to be able to determine the low and high temperatures so far programming tools? pseudo-code?

pseudo-code: no array version PROMPT FOR & READ FILE NAME; if (READ FIRST TEMP OK) { SET LOW TO TEMP; SET HIGH TO TEMP; while (READ ANOTHER OK){ if (HIGHER THAN HIGH) { UPDATE HIGH; } else if (LOWER THAN LOW){ UPDATE LOW; } DISPLAY HIGH & LOW; } else { DISPLAY ERROR MESSAGE; } must read in all temps  keeping track of lowest and highest values seen so far  when done reading all temps, then have lowest & highest could structure the code lots of ways  how should low & high be initialized?

temp extremes (no array) // temp.cpp //////////////////////////////////////////// #include using namespace std; int main() { string tempFile; cout << "Enter the temperature file name: "; cin >> tempFile; ifstream ifstr; ifstr.open( tempFile.c_str() ); while (!ifstr) { cout << "File not found. Try again: "; cin >> tempFile; ifstr.clear(); ifstr.open( tempFile.c_str() ); } int temp; if (ifstr >> temp) { int lowTemp = temp; int highTemp = temp; while (ifstr >> temp) { if (temp > highTemp) { highTemp = temp; } else if (temp < lowTemp) { lowTemp = temp; } cout << "Low temperature: " << lowTemp << endl; cout << "High temperature: " << highTemp << endl; } else { cout << "There were no temps!" << endl; } ifstr.close(); return 0; }

pseudo-code: array version PROMPT FOR & READ FILE NAME; READ TEMPS & STORE IN ARRAY; if (ANY TEMPS WERE READ) { GET & DISPLAY LOW TEMP; GET & DISPLAY HIGH TEMP; } else { DISPLAY ERROR MESSAGE; } can use a more top-down approach if we instead read in and store the temperature in an array  not necessarily as efficient, but easier to understand and code  tasks are separated, can be coded and tested independently

temp extremes (array version) // temp.cpp //////////////////////////////////////////// #include using namespace std; const int MAX_TEMPS = 24*60; void ReadTemps(int temps[], int & numTemps); int GetLowest(const int temps[], int numTemps); int GetHighest(const int temps[], int numTemps); int main() { int temps[MAX_TEMPS], numTemps; ReadGrades(temps, numTemps); cout << "The lowest temperature was: " << GetLowest(temps, numTemps) << endl; cout << "The highest temperature was: " << GetHighest(temps, numTemps) << endl; return 0; } /////////////////////////////////////////////// void ReadTemps(int temps[], int & numTemps) // Results: reads temps and stores in array // numTemps is set to the # of temps { string tempFile; cout << "Enter the temperature file name: "; cin >> tempFile; ifstream ifstr; ifstr.open( tempFile.c_str() ); while (!ifstr) { cout << "File not found. Try again: "; cin >> tempFile; ifstr.clear(); ifstr.open( tempFile.c_str() ); } numTemps = 0; int temp; while (numTemps > temp){ temps[numTemps] = temp; numTemps++; } ifstr.close(); }

array version (cont.) int GetLowest(const int temps[], int numTemps) // Assumes: temps contains numTemps temperatures // numTemps > 0 // Returns: the lowest temp in the array { int lowest = temps[0]; for (int i = 1; i < numTemps; i++) { if (temps[i] < lowest) { lowest = temps[i]; } return lowest; } int GetHighest(const int temps[], int numTemps) // Assumes: temps contains numTemps temperatures // numTemps > 0 // Returns: the highest temp in the array { int highest = temps[0]; for (int i = 1; i < numTemps; i++) { if (temps[i] > highest) { highest = temps[i]; } return highest; } once temperatures have been stored in an array, GetLowest and GetHighest functions are:  straightforward  similar  independent

file output similarly, it is possible to direct program output to a file  must declare an output file stream (ofstream)  open using a file name (same as with ifstreams)  write using <<  close when done (same as with ifstreams) #include // loads definition of the output // file stream class (ofstream)... ofstream myout;// declares output file stream myout.open("nums.out");// opens the output file stream // using the file "nums.out" for (int i = 0; i < 100; i++) {// writes numbers to output file, myout << i << endl;// one per line } myout.close();// closes the output file stream

updating the grade file suppose we wanted to scale up the grades in the file  can read the grades from a file  write the updated grades back to that same file PROMPT FOR & READ FILE NAME; OPEN INPUT FILE STREAM; READ GRADES & STORE IN ARRAY; CLOSE INPUT FILE STREAM; PROMPT FOR BONUS AMOUNT; SCALE UP GRADES; OPEN OUTPUT FILE STREAM; WRITE UPDATED GRADES; CLOSE OUTPUT FILE STREAM; note: storing the grades in an array is necessary a file can't be opened for input & output at the same time

#include using namespace std; const int MAX_GRADES = 100; void ReadGrades(int grades[], int & numGrades, string & fname); void ScaleUp(int grades[], int numGrades); void WriteGrades(const int grades[], int numGrades, string fname); int main() { int grades[MAX_GRADES], numGrades; ReadGrades(grades, numGrades); ScaleUp(grades, numGrades); WriteGrades(grades, numGrades, fileName); return 0; } ////////////////////////////////////////////// void ReadGrades(int grades[], int & numGrades, string & fname) // Results: reads grades and stores in array // numGrades is set to the # of grades // fname is the name of the input file { // AS BEFORE, EXCEPT FOR THE FILE NAME } void ScaleUp(int grades[], int numGrades) // Assumes: grades contains numGrades grades // Results: a bonus is added to each grade { int bonus; cout << "How many bonus points are there? "; cin >> bonus; for(int i = 0; i < numGrades; i++) { grades[i] += bonus; if (grades[i] > 100) { grades[i] = 100; } void WriteGrades(const int grades[], int numGrades, string fname) // Assumes: grades contains numGrades grades // Results: writes updated grades back to fname { ofstream ofstr; ofstr.open(fname.c_str()); for (int i = 0; i < numGrades; i++) { ofstr << grades[i] << endl; } ofstr.close(); } updating the grade file

copy cat? would the following code suffice to copy the contents of a file? i.e., does copy.txt look exactly like the input file? // copy.cpp //////////////////////////////////// #include using namespace std; int main() { string infile; cout << "Enter the input file name: "; cin >> infile; ifstream ifstr; ifstr.open(infile.c_str()); ofstream ofstr; ofstr.open("copy.txt"); char ch; while (ifstr >> ch) { ofstr << ch; } ifstr.close(); ofstr.close(); return 0; }

real copy cat recall that >> ignores all whitespace  thus, the previous program will copy all non-whitespace chars, but spacing will be lost the get member function (from ) reads a character, including whitespace  applied to an input stream  one argument: a char // copy.cpp //////////////////////////////////// #include using namespace std; int main() { string infile; cout << "Enter the input file name: "; cin >> infile; ifstream ifstr; ifstr.open(infile.c_str()); ofstream ofstr; ofstr.open("copy.txt"); char ch; while (ifstr.get(ch)) { ofstr << ch; } ifstr.close(); ofstr.close(); return 0; }

faster copy cat the getline function (from ) reads an entire line of text, including whitespace  two arguments: input stream and a string note inconsistency:  get is a member function  getline is a stand-alone function // copy.cpp //////////////////////////////////// #include using namespace std; int main() { string infile; cout << "Enter the input file name: "; cin >> infile; ifstream ifstr; ifstr.open(infile.c_str()); ofstream ofstr; ofstr.open("copy.txt"); string line; while (getline(ifstr, line)) { ofstr << line << endl; } ifstr.close(); ofstr.close(); return 0; }

file I/O summary can read input from files  declare an input file stream ( ifstream ), as defined in  open the input file stream using a file name (C-style string)  read data using >>, same as with cin  close the input file stream when done can write output to files  declare an output file stream ( ofstream ), as defined in  open the output file stream using a file name (C-style string)  write data using <<, same as with cout  close the output file stream when done alternatives to >> exist that don't ignore whitespace  get reads a character (including whitespace)  getline reads an entire line of text (including whitespace)