320 likes | 478 Views
Prerequisite Review. CS215 UK Computer Science. Why Review?. There are several major skills which are necessary from day one in CS215 that incoming students often have not learned or mastered. Manipulating Input and Output Streams File Input and Output Stream States Sentinel Loop Logic
E N D
Prerequisite Review CS215 UK Computer Science
Why Review? • There are several major skills which are necessary from day one in CS215 that incoming students often have not learned or mastered. • Manipulating Input and Output Streams • File Input and Output • Stream States • Sentinel Loop Logic • Sentinel Loops • End of File Loops • Arrays • Declaration, Use, and Traversal
Manipulating I/O Streams • Streams are special locations in memory through which input and output flow • An input stream is a source of input data, and an output stream is a destination for output data • Some default streams exist, but most streams are defined by the programmer, much like a variable
Stream Operations • Streams are not magic! • Operations must be performed on the streams in order to gather input or produce output. • Each stream operation effects the reading or writeing marker (cursor) in some way. • By knowing how each command effects the cursor, you can master input and output!
Stream Operations • Common Input Operations • >> (extraction) • getline • ignore • Common Output Operations • << (insertion) • endl
Console I/O • Console I/O refers to input and output using the keyboard and monitor • “cin” and “cout” are predefined streams • “cin” is an input stream lining your program to the keyboard • “cout” is an output stream linkint your program to the monitor
An Example #include <iostream> //include library for console I/O //variables “cin” and “cout” are declared in this library #include <string> using namespace std; //apply the standard namespace int main() { int X; //declare an integer variable named X string Sentence; //declare a string variable named sentence cout<<“Please enter an positive integer: ”; //prompt cin>>X; //extract the next integer from the input stream “cin” //store that extracted data into the variable called “X” cout<<“Please type a sentence:”<<endl; //prompt cin.ignore(255,’\n’); //Why is there an ignore here? getline(cin, sentence); //get the next line of input from “cin” //store that line into the variabel called “sentence” for( inti=0; i<X; i++ ) cout<<sentence<<endl; //output the sentence on X lines return 0; }
Output Manipulation • Simply inserting items to the output stream using << provides limited control of the output appearance. • tabs and new lines • There is a library available which provide greater control of output appearance. • scientific or decimal output • precision of decimal output • column alignment
The <iomanip> Library • Common Output Manipulation • fixed – disable scientific notation • showpoint – show the decimal point • setprecision – display a given number of digits past the decimal point • setw – set the character width of the next output item • There are more which we won’t use…
An Example #include <iostream> //include library for console I/O #include <iomanip> //include library for stream manipulation #include <string> using namespace std; //apply the standard namespace const float PI = 3.14159; int main() { cout<<fixed; //disable scientific notation for the cout stream cout<<showpoint; //have the cout stream show decimal points cout<<setprecision(4); // have the cout stream show 4 places cout<<PI<<endl<<endl; //what will be output? //output a table with columns aligned cout<<setw(8)<<“Pi”<<setw(12)<<“Multiplier”<<setw(10)<<“Result”; cout<<endl; cout<<setw(8)<<PI<<setw(12)<<2<<setw(10)<<2*PI<<endl; cout<<setw(8)<<PI<<setw(12)<<3<<setw(10)<<3*PI<<endl; cout<<setw(8)<<PI<<setw(12)<<4<<setw(10)<<4*PI<<endl; }
The Output 3.1416 1234567890123456789012345678901234567890 Pi Multiplier Result 3.1416 2 6.2832 3.1416 3 9.4248 3.1416 4 12.5664 Press any key to continue . . . setw(8) width of 8 positions 1-8 right-aligned setw(12) width of 12 positions 9-20 right-aligned setw(10) width of 10 positions 21-30 right-aligned
File I/O • The same input and output operations can be performed using files as the source or destination. • Input and Output streams connected to files must be created by the programmer, unlike “cin” and “cout” which are already created.
Five Steps for Using File I/O 1) Include the <fstream> library 2) Declare your file stream variables… “ifstream” type for input files “ofstream” type for output files 3) Open the file streams to associate them with the file on disk 4) Use your file stream variables as you would use any other I/O stream >>, getline, ignore <<, endl, fixed, showpoint, setprecision, setw 5) Close your file stream variables
An Example #include <iostream> //include library for I/O commands #include <fstream> //include library for file I/O #include <string> using namespace std; //apply the standard namespace int main() { int X; //declare an integer variable named X string Sentence; //declare a string variable named sentence ifstreamfileIn; //declare an input file stream named “fileIn” fileIn.open(“data.txt”); //connect “fileIn” to the file “data.txt” fileIn>>X; //extract the next integer from the file stream fileIn.ignore(255,’\n’); //Why is there an ignore here? getline(fileInin, sentence); //get the next line of file input for( inti=0; i<X; i++ ) cout<<sentence<<endl; //output the sentence on X lines return 0; }
Stream States • File streams can enter a “fail state” during operation. • Any further I/O operation on a stream which is in a fail state is not performed properly Thus, you can get garbage input, no output, and your program is ineffective. • Even worse, no error or warning message is given, and the program does not terminate!
Causes of a Fail State • Input File Streams Enter a Fail State When… • You try to open a file that doesn’t exist or cannot be found. • You try to read data of an incompatible type. • You try to read past the end of the file. • Output File Streams Enter a Fail State When… • You try to create a file with an invalid name. • You try to create/write to a write-protected file. • You try to create/write to a file on a full device.
Determining the Stream State • Luckily, it is simple to check the state of a file stream to determine if any of these things have occurred! • The name of the stream can be used as a Boolean variable to check stream state! • TRUE – Stream State is OK • FALSE – Stream is in Fail State
An Example ifstream fin; int data; fin.open(“data.txt”); if( ! fin ) //if the bool value of “fin” is false { cout<<“Input file not opened properly!”<<endl; exit(0); //exit program } fin >> data; if( fin ) //if the bool value of “fin” is true cout<<“First piece of data is: “<<data<<endl; fin >> data; if( fin ) //if the bool value of “fin” is true cout<<“Second piece of data is: “<<data<<endl;
Sentinel Loop Logic • The word sentinel refers to an entity which protects something from unintended entry. • Sentinel Loop Logic refers to a loop which is explicitly designed to prevent bad data from being used in processing. • The processing part of the loop cannot be entered if the data is bad!
Loop Systems Which UseSentinel Logic • Sentinel Loops • Data is repeatedly read in and processed until a special data value is encountered. This special value is called the sentinel value. • EXAMPLE: Read some test scores from the KB. Continue reading test scores until you encounter -1. • End of File (EOF) Loops • Data is repeatedly read in from a file and processed until bad data is encountered or the end of the file is reached. • EXAMPLE: Read all test scores in from the file. There are an unknown number of scores.
Loops Using Sentinel LogicRequire a “Priming Read” --This code does not work properly!-- --Why? In what cases?-- int testScore; int scoreSum = 0, scoreCount = 0; float average; while( testScore != -1 ) { cin >> testScore; //read in the next test score //process this test score scoreSum = scoreSum + testScore; scoreCount ++; } average = float(scoreSum) / float(scoreCount);
Corrected Code int testScore; int scoreSum = 0, scoreCount = 0; float average; cin >> testScore; //prime read first test score while( testScore != -1 ) { //process this test score scoreSum = scoreSum + testScore; scoreCount ++; cin >> testScore; //read in the next test score } average = float(scoreSum) / float(scoreCount);
A Correct EOF Loop int scoreSum = 0, scoreCount = 0; float average; ifstrem fin; fin.open(“data.txt”); fin >> testScore; //prime read first test score while( fin ) //stop if file enters fail state { //process this test score scoreSum = scoreSum + testScore; scoreCount ++; fin >> testScore; //read in the next test score } average = float(scoreSum) / float(scoreCount);
Benefits of Correct EOF Loop • Does not enter loop if… • File is not opened properly. • File is empty. • Loop stops and only valid data is processed if… • An invalid data entry is encountered. • The end of the file is encountered. • Does not go through loop one too many or one too few times.
Arrays • An array (also called a vector) is a linear collection of data which is given a single name. • Each element in the array is of the same data type. • Each element in the array can be accessed individually through an index. • The name of the array refers to the beginning of the collection in memory (the “base address”) • Indexes into the array are offset from the base address • index 0 is the first item, index 3 is the fourth item, etc…
Declaring an Array • Declare an array called temps which will hold up to 5 individual float values float temps[5]; // Declaration allocates memory number of elements in the array Base Address 7000 7004 7008 7012 7016 temps[0] temps[1] temps[2] temps[3] temps[4] indexes or subscripts
Accessing Array Components • When you declare an array… • dataType name[constsize]; • A piece of memory appropriately sized for constsize instances of dataType is reserved and given the specified name • cout<<name; //DOES NOT WORK • When you give the name of the array, the compiler retrieves the beginning (base address) of the array, not any of the contents • cout<<name[intindex]; //WORKS • By providing an index, you are effectively telling the compiler “start at the beginning of this array and jump forward intindex spaces, give me the value there
Array Traversal • Often it is useful to scan through each cell in an array to operate on each piece of information (for example to initialize them), this is known as traversal. • Does it make sense to traverse an array like this? Arr[0] = 0; Arr[1] = 0; … Arr[1000] = 0;
Array Traversal • Array traversal can more easily be done using a counter controlled loop. Initialize the counter to 0 and set the stopping criteria to the array size. for(int i=0; i<1000; i++) Arr[ i ] = 0;
Parallel Arrays 0 Parallel arrays are two or more arrays that have the same index range and whose elements contain related information, possibly of different data types EXAMPLE const int SIZE 50; int idNumber[SIZE]; float hourlyWage[SIZE]; parallel arrays
0 const int SIZE 50;int idNumber[SIZE]; // Parallel arrays holdfloat hourlyWage[SIZE]; // Related information • idNumber[0] 4562 hourlyWage[0] 9.68 • idNumber[1] 1235 hourlyWage[1] 45.75 • idNumber[2] 6278 hourlyWage[2] 12.71 • . . . . • . . . . • . . . . • idNumber[48] 8754 hourlyWage[48] 67.96 • idNumber[49] 2460 hourlyWage[49] 8.97
For Further Review… • Look at the resources on the lecture part of the course web page. • Look at the CS115 notes: http://www.cs.uky.edu/~keen/115/115.html