Program I/O & Version Control
COSC1076 Week 05
Software Problem Solving
Copyright By PowCoder代写 加微信 powcoder
Problem Solving
Problem Solving is about find software solutions to problems • It’s an obvious statement, but what does it actually mean?
Software Design
Implementation
Week 05 | Program I/O & Version Control COSC1076
Review: Program I/O
What we’ve seen so far
We have briefly examined how to go simple I/O to the “terminal” • Reading in information that a user types from the “terminal” • Writing out information to the user on the “terminal”
Week 05 | Program I/O & Version Control COSC1076
Standard I/O – C++ STL (cout)
For output, use the cout object
• Contained in the
Uses the output operator (<<)
Standard I/O – C++ STL (cin)
What about:
• End of input?
• Input error or failure?
cin is an object – you should be familiar with these from Java • Has functions to check for these things
– eof() – check for end of file
– fail() – check for read error
• (More on classes and objects next week)
Week 05 | Program I/O & Version Control COSC1076
Program Layout
Declaration vs Definition vs Initialisation
Declaration
• Introduce a name (variable, class, function) into a scope • Fully specify all associate type information
Definition
• Fully specify (or describe) the name/entity
• All definitions are declarations, but not vice versa
Initialisation
• Assign a value to a variable for the first time
Week 05 | Program I/O & Version Control COSC1076
Forward Declaration
A Forward Declaration is a statement that declares the existence of a name or entity, without defining that entity
Typically used with:
• Functions (function prototype) • Classes
// Forward Declare Card Type
class Card;
class Hand {
Card* Cards[LENGTH];
Week 05 | Program I/O & Version Control COSC1076
Function/Method Overloading
Function/Method Overloading
Overloading is where the same name is used for multiple functions/methods • The overloaded functions/methods must have different types**
– In C++ this means the parameters must be different
– Be careful about auto-type casting (see later lecture)
• The overload method that is called is determined by the method’s type
Differs to shadowing, since all versions of the function/method can be called
** Some languages (such as Haskell) allow the functions to have the same parameters, but return different types.
Week 05 | Program I/O & Version Control COSC1076
Function/Method Overloading
The overloaded method that is called is determined by the method’s type • This is the parameters of the function or method
int printCard(Card& card); int printCard(Card* card);
int printCard(Colour colour, int number);
• You cannot overload by changing the return type, eg. this will not work
int getColour();
std::String getColour();
Week 05 | Program I/O & Version Control COSC1076
Constructor Overloading
Multiple constructors can be created on a class
• Strictly this “overloads” the constructor operator
• We’ve already seen this through default, “normal” and copy constructors! • Of course other constructors can be defined
Card(int colour, int number);
Card(std::string colour, int number);
Card(Card& other);
Week 05 | Program I/O & Version Control COSC1076
Constructor “Chaining”
A constructor can call another constructor if it provides more flexibility • This saves on code-duplication and allows logic to be reused
Card::Card() :
Card(0, 0)
Card::Card(Card& other) :
Card(other.number, other.colour)
Week 05 | Program I/O & Version Control COSC1076
Program I/O
Input/Output Sources
There are 2 typical sources of input and output for programs • Standard I/O – aka “the terminal”
• File I/O
These are the two we will use in COSC1076
Other sources of I/O may include:
• Network I/O (from TCP/UDP connections) • External Computer Devices such as:
– Microphone – Speaker
Week 05 | Program I/O & Version Control COSC1076
Standard I/O
Standard I/O is the “standard” communication channel between a program and the operating system
Generally, the “standard” channel is:
• Directly connected to the computer’s User I/O
• That is, the computer keyboard and screen/monitor
• For programs run through the terminal, the terminal provides the standard keyboard and screen interface
Standard I/O is divided into 3 streams:
• stdin (standard input) – typically the keyboard (via the terminal)
• stdout (standard output) – typically the screen/terminal
• stderr (standard error) – typically the screen/terminal, explicitly for error reporting
Week 05 | Program I/O & Version Control COSC1076
File I/O refers to:
• Anything stored on the physical hard drive (disk) of the computer
• Physical external storage devices (including network mounted devices) • Printers
Care must be taken to ensure:
• The data on the hard drives & external drives is not corrupted
• Other programs do not modify the files while our program is using them
In COSC1076, File I/O will deal with “files” stored on the local computer
Week 05 | Program I/O & Version Control COSC1076
Abstracting I/O
Does the exact location of the I/O matter to a program?
Week 05 | Program I/O & Version Control COSC1076
Abstracting I/O
Does the exact location of the I/O matter to a program?
• Reading/Writing from files or standard locations is the same concept
I/O is abstracted into I/O streams
Week 05 | Program I/O & Version Control COSC1076
I/O Streams
A stream is:
• A method to communicate with any device
• A consistent interface for the programmer
• Independent of the actual device being used
• A level of abstraction between the programmer and the device • Can write to disk file or another type of device (e.g. console)
• Has two types: (1) text streams; (2) binary streams
A device may be:
• Standard I/O
• Files (local & on external hard drives) • Network connections
• External devices
Week 05 | Program I/O & Version Control COSC1076
Binary Streams
Binary Streams
• A sequence of bytes (1’s and 0’s)
• No character translation occurs
• There is a 1-to-1 correspondence between bytes of the stream and the actual device
• May contain a certain number of null bytes at the end
– For example, for padding so the file fills a sector on a disk
Week 05 | Program I/O & Version Control COSC1076
Text Streams
Text Streams
• A sequence of characters
• Can be organised into lines terminated by a newline character
– Optional for the last line
• Character translation may occur as required by the host environment
• For example:
– newline → carriage return / linefeed [when writing]
– Carriage return / linefeed ← newline [when reading]
• Not necessarily a 1-to-1 relationship between characters of the stream and the actual device
Week 05 | Program I/O & Version Control COSC1076
Program I/O in C++
Writing (ostream)
An output stream (ostream) allows content to be “written to” the stream Output is performed with the << operator
std::ostream& outputStream = std::cout;
outputStream << "Some output" << endl;
An ostream is a generic C++ class, of which there can be multiple implementations
• The output operator is defined as:
• Where T is some type
• Note how it returns a reference to an output stream!
operator<<
Week 05 | Program I/O & Version Control COSC1076
Creating an Output Stream
The output stream for standard output is std::cout • This the form of output we have used most often
Week 05 | Program I/O & Version Control COSC1076
Writing to a File
To write to a file, a file output stream is required • std::ofstream class
• Found in fstream header file
Similar to using std::cout, except:
• Before writing, must open the file (for writing)
- When opening a file, provide the file name • When done, must close the file
- This is so your OS knows you are finished using the file
When opening, there are two modes
• Normal - creates a new files, erasing any exiting file with the same name • Append - add to the end of an existing file
Week 05 | Program I/O & Version Control COSC1076
Writing to a File
std::string filename("file.txt");
Filename - Relative Path File output stream
Open for normal output Write
Close file
Open for Appending
std::ofstream outFile;
outFile.open(filename);
outFile << "Writing to File" << endl;
outFile.close();
outFile.open(filename, std::ofstream::app);
outFile << "Appending to File" << endl;
outFile.close();
Week 05 | Program I/O & Version Control COSC1076
Checking the Status of Output Streams
It may be necessary to check the “status” of the output stream • The ostream class has methods to do this
It may also be necessary to “flush” the stream to ensure the contents is written • Typically a stream automatically flushes after every newline
Check whether state of stream is good
Check whether either failbit or badbit is set
Flush output stream buffer
Week 05 | Program I/O & Version Control COSC1076
Reading (istream)
An input stream (istream) allows content to be “read from” the stream Input can be performed with the >> operator
std::istream& inputStream = std::cin;
double value;
inputStream >> value;
std::cout << "Read: " << value << std::endl;
An istream is a generic C++ class: • The input operator is defined as:
• Where T is some type
• Note how it returns a reference to an input stream!
operator>>
Week 05 | Program I/O & Version Control COSC1076
Creating an Read Stream
The output stream for standard input is std::cin
Week 05 | Program I/O & Version Control COSC1076
Reading from a File
To read from a file, a file input stream is required • std::ifstream class
• Found in fstream header file
Functions similar to std::ofstream:
• File must be opened/closed
• Reading may fail if the opened file does not exist
Week 05 | Program I/O & Version Control COSC1076
Checking the Status of Read Streams
The “status” of an input stream is checked similar to output streams A special check is if the end-of-input (^D character) is reached
Check whether state of stream is good
Check whether either failbit or badbit is set
Check if EOF is reached
Week 05 | Program I/O & Version Control COSC1076
Technical Details
The >> read operator only reads the next valid token from the input stream
• The validity of a token is based on the type of the variable that is being read • Token are always separated by whitespace
• Whitespace is not read!
– This includes spaces and newlines
– Even if std::string is used, whitespace is ignored
Week 05 | Program I/O & Version Control COSC1076
Alternative Read methods
The istream class provides alternative methods for reading, depending on precisely how the input needs to be handled
Extract a single character from the stream
istream& getline(char* s,
streamsize n );
Read a whole line into a string, including whitespace and newline characters, up to a maximum number of characters
The string STL library provides an alternative get line that works with strings
std::getline(istream& is,
string& str);
Read a whole line into a string, including whitespace and newline characters
Week 05 | Program I/O & Version Control COSC1076
String Processing
String Streams (stringstream)
Input and Output streams can be generated from std::string’s
They use the same operators/methods: • << operator
• >> operator
• good/bad/eof
They do no require opening/closing
String streams are useful for:
• Loading data before processing it • Modularisation of I/O processing
Located in sstream STL file
Week 05 | Program I/O & Version Control COSC1076
Recall that a c-string is just an array of characters
Week 05 | Program I/O & Version Control COSC1076
std::string Class – Indexing
A std::string is a class that “nicely” wraps a c-style string
• Provides useful methods for interacting with the string
• Can still interact with the std::string in the style of an array • We don’t “see” the \0 terminating character
Each character in the string can be individually accessed
Lookup cell (index) using square bracket notation, similar to using an array. No bounds checking!
at(
Method that is the same as using square brackets. With bounds checking
Week 05 | Program I/O & Version Control COSC1076
std::string Class – Methods
Other methods on the class include
Returns the number of characters
Reverse the string
append(string)
Append a given string to the end of this string
substr(int,int)
Return the sub-string between two locations
Get a c-style version of the string
Week 05 | Program I/O & Version Control COSC1076
std::string Class – Operators
The class can also be used with typical operators
Assignment. Copies one string into another
Combine two string into a third string. Copies the contents
Compare for equality/inequality
Compare for lexical ordering
We will see how to do this in week 10.
Week 05 | Program I/O & Version Control COSC1076
Lexical Comparison of Strings
Two string can be compared for lexical ordering.
• That is not necessarily the order which the two strings appear in a dictionary • The comparison uses ASCII (or unicode) values
Each character of the string is compared one-at-a-time, in order until two characters differ
• The character with the small ASCII value is lexicographically first • Otherwise, the smaller string comes first
compare (<) < < < <
Week 05 | Program I/O & Version Control COSC1076
Command Line Arguments
Command Line Arguments
Command line arguments are options placed on the terminal after the name of the program
• Arguments are separated by any amount of whitespace
./program_name arg1 arg2 arg3
Command (Program Name)
Argument(s)
Technically the name of the command/program is also an argument!
Week 05 | Program I/O & Version Control COSC1076
Command Line Arguments
Arguments are passed to a C++ program using a special set of parameters for the main function
int main(int argc, char** argv) {
Number of Arguments as 2D Arguments Array of strings
If a program does not require the arguments, the void type is used
int main(void) {
Week 05 | Program I/O & Version Control COSC1076
Command Line Arguments
int main(int argc, char** argv) {
The program name is always the first argument
• Will always be at least 1
• An array of c-style strings
• Each string in argv is guaranteed to be null-terminated
• For our purposes, the easiest thing to do is to convert the c-style string into std::string’s
Week 05 | Program I/O & Version Control COSC1076
C++ Online Documentation
Online C++ References
For classes and header files that we are using, links will be given to the relevant documentation. These are listed on Canvas for each week
•
•
– std::osftream
•
Main websites:
• Official Language Reference • C++.com
Week 05 | Program I/O & Version Control COSC1076
Online C++ References
Be careful
• These sites are the definitive documentation and can be quite confusing • Most classes we have seen are complex generic types
– The types that we use are generated by typedef’s!
• But don’t be alarmed, the information you need is there and simple to extract
Week 05 | Program I/O & Version Control COSC1076
“Randomness” in Programs
What is Random?
Week 05 | Program I/O & Version Control COSC1076
What is Random?
So called “true” randomness is where a sequence lacks any: • Identifiable Pattern
• Predictability
• Ordering
Human’s are very poor at identifying randomness, typically because of the gambler’s fallacy.
As every algorithm (and Turing complete machine) is a sequence of instructions, it is impossible to generate a truely random sequence
Week 05 | Program I/O & Version Control COSC1076
Pseudo-Randomness
Computers can generate a pseudo-random number sequence.
• To an outside observer the sequence displays statistical randomness
– Where any number is the sequence cannot be predicted
However, under-the-hood, each number is the sequence is algorithmically produced using the preceding number(s)
• The sequence is initialised by a seed
• Only if the seed is known is it possible to predict the sequence • Hence the name, pseudo-random
Week 05 | Program I/O & Version Control COSC1076
C++ Pseudo-random Number Generation
C++ has very mathematically complex ways to generate random numbers. • In this course, we are just going to use a very simple paradigm
• We will generate random integers between a minimum and maximum
This requires two entities
• Engine – the algorithm that generates random numbers,
– Typically a uniform distribution of integers
• Distribution – a mathematical formula that transforms the output of the engine into another sequence of value with varying properties
Both come from the random header file
Week 05 | Program I/O & Version Control COSC1076
C++ Pseudo-random Number Generation
int min = 1;
int max = 10;
int seed = 100;
std::default_random_engine engine(seed);
std::uniform_int_distribution
int value = -1;
for (int i = 0; i != 10; ++i) {
value = uniform_dist(engine);
cout << "Randomly-chosen value: " << value << endl;
Week 05 | Program I/O & Version Control COSC1076
C++ Pseudo-random Number Generation
If the engine is given the same seed, it will produce the same random sequence
To get a “random” seed (typically taken from the computer internal clock) a different engine can be used:
•std::random_device engine
Week 05 | Program I/O & Version Control COSC1076
Group Development & Version Control
Version Control with Git
Some of you will be familiar with this already
Many software manage system (SMS’s) exist to help developers manage and collaborate on creating software.
Git is a popular tool (for now)
• Git is highly configurable for many different purposes • Git has many different functionalities
• We will use Git in a very simple model
- You can go as far “down the rabbit hole” as you want
Week 05 | Program I/O & Version Control COSC1076
Centralised Git Model
A simple model uses a central repository for a code base
• Users push and pull changes to the code base to/from the repository • Code changes are grouped into a block termed a commit
Central Code Repository
Week 05 | Program I/O & Version Control COSC1076
A commit is a “diff” (difference) in how the files of the code base have changed from their previous state, to their new state
Commits are chained together to form a history of code changes
The head of the history is the most current (most up-to-date) version of the
codebase, applying all of the commit from the start of the history
History of changes
Week 05 | Pro
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com