Title: Learning by Example Dissection of Example Program (cont
1Learning by Example Dissection of Example
Program (contd)
- / Example program computes prints users age
in days - Course CS 2308-xxx Author ...
Date ... - ... /
- include ltiostream.hgt
- int main(void)
-
- const int DAYS_PER_YEAR 365 // constant
declaration - int ageInYears, ageInDays // variable
declarations - cout ltlt "Enter your age in years (whole
number) " - cin gtgt ageInYears
- ageInDays ageInYears DAYS_PER_YEAR
- cout ltlt "Your age is about " ltlt ageInDays ltlt "
days.\n" - return(0)
2Dissection of Example Program (contd) C I/O
Objects
- Defined in iostream.h header file for standard
class called iostream - Of particular interest in this course
- Important aspects of interactive I/O file I/O
- Interactive I/O
- Reading from or writing to system monitor
- Need for this is obvious
- File I/O
- Reading from or writing to file on disks
- Required for most homework assignments
3Dissection of Example Program (contd)
Interactive Output Using cout Statement
- Syntax
- cout ltlt expr1 ltlt expr2 ltlt expr3 ltlt ltlt exprN
- cout - output stream object connected to system
monitor - ltlt - stream insertion operator
- expr1, , exprN - placeholders for valid C
expressions - stream - sequence of data
- What happens
- Items are inserted into output stream using
stream insertion operator - As items are inserted into output stream, they
flow to system monitor - Overall effect sequence of data displayed on
system monitor
4Dissection of Example Program (contd)
Interactive Output Using cout Statement (contd)
- cout ltlt 250 gives 250
- cout ltlt 7.89 gives 7.89
- cout ltlt A gives A
- cout ltlt A String gives A String
- cout ltlt 1 ltlt 2 ltlt 3 gives 123
- No automatic generation of spacing between items
- cout ltlt 1 ltlt ltlt 3 gives 1 3
- cout ltlt ageInDays gives ltvalue of ageInDaysgt
- ageInDays being a defined variable
- In example program
- cout ltlt "How old are you in years?\n"
- cout ltlt "Your age is about " ltlt ageInDays ltlt
"\n" - \n ? escape sequence for newline ( carriage
return/line feed)
5Dissection of Example Program (contd)Digression
Escape Sequences
- Used in C/C to represent nonprinting characters
(tab, newline, etc.), and special characters like
", ', / and \. - Each consists of backslash (\, the escape
character) followed by one or more characters
(e.g., \n for newline) - Represent single characters, though each written
as more than one character - When encountering \, insertion operator looks
ahead at the next character(s) combines it/them
with the backslash to form an escape sequence -
\ gives signal to escape from normal way of
interpretation
6Dissection of Example Program (contd)
Digression Escape Sequences (contd)
- Some Common Escape Sequences
- Escape Sequence Meaning
- \f form feed (move to next page)
- \n newline (move to next line)
- \t horizontal tab (move to next tab setting)
- \\ backslash ( \ )
- \ single quote ( ' )
- \ double quote ( " )
7Dissection of Example Program (contd)
Digression \n versus endl
- Newline escape sequence (\n)
- Generates carriage return/line feed
- End-of-line manipulator (endl)
- Generates carriage return/line feed
- Flushes stream buffer
- Some systems accumulate information in buffer
until there is enough to justify flushing - endl manipulator forces any accumulated buffer
information to be flushed immediately - When to use which
- Use \n within cout statement for cursor
control - Use endl manipulator at end of cout statement
to flush buffer
8Dissection of Example Program (contd)
Digression \n versus endl (contd)
- Example
- Assuming current, resistance and voltage are
defined variables with - values of 0.001, 4700 and 4.7, respectively, the
cout statement - cout ltlt "With a current of " ltlt current ltlt "amp
and a\n" - ltlt "resistance of " ltlt resistance ltlt "ohm,
the\n" - ltlt "voltage is " ltlt voltage ltlt " volt." ltlt
endl - generates the output
- With a current of 0.001 amp and a
- resistance of 4700 ohm, the
- resulting voltage is 4.7 volt.
- Applying to example program
- cout ltlt "How old are you in years?" ltlt endl
- cout ltlt "Your age is about " ltlt ageInDays ltlt endl
9Dissection of Example Program (contd)
Digression Formatted Output Using Manipulators
(iomanip.h)
- setw(width)
- Display next value in a field with specified
width (integer) - Default is 0, automatically grows to accommodate
- setprecision(precision)
- Display values with specified precision (integer)
- Usual default is 6
- setiosflags( flag1 flag2 ... flagN )
- Set formatting flag(s) like
- iosshowpoint - display decimal point
trailing zeroes - iosfixed - display real values in
fixed-point form - iosscientific - display real values in
floating-point form - iosleft - display values left-justified
within field - iosright - display values right-justified
within field
10Dissection of Example Program (contd)
Digression Formatted Output Using Manipulators
(contd)
- Example
- Given that x y are defined variables with
values of 1.234 5, the output statement - cout ltlt setiosflags(iosshowpoint iosfixed)
- ltlt setprecision(3) ltlt "\n("
- ltlt setw(10) ltlt x ltlt ")\n("
- ltlt setw(10) ltlt y ltlt ")" ltlt endl
- generates the output
- ( 1.234)
- ( 5.000)
11Dissection of Example Program (contd)Digression
Formatted Output Using Member Functions
- Example (Using Stream Object Member Functions)
- Given that x y are defined variables with
values of 1.234 5, the output statements - cout.setf(iosfixed)
- cout.setf(iosshowpoint)
- cout.precision(3)
- cout.width(10)
- cout ltlt "\n(" ltlt x ltlt ")\n(" ltlt y ltlt ")" ltlt
endl - generates the output
- ( 1.234)
- ( 5.000)
12Dissection of Example Program (contd)
Interactive Input Using cin Statement
- Syntax cin gtgt var1 gtgt var2 gtgt var3 gtgt gtgt
varN - cin - input stream object connected (by
default) to system keyboard - gtgt - stream extraction operator
- var1, , varN - variables defined in program
- Notes
- gtgt operator extracts data items to be read from
input buffer - Items extracted are assigned, in respective
order, to listed variables - Variables must be defined prior to appearing in
cin statement - Any white space (spaces, tabs or newlines) can be
used to separate data items (gtgt operator ignores
all white-space characters) - Program execution is suspended until all
extraction operations in an input statement are
complete - Good practice to precede cin statements with
appropriate prompts
13Dissection of Example Program (contd)
Interactive Input Using cin Statement (contd)
- Examples
- Single data item
- cin gtgt x
- Multiple data items
- cin gtgt x gtgt y gtgt z
- In example program (prompt preceding cin
statement) - cout ltlt "How old are you in years?\n"
- cin gtgt ageInYears
- cout is flushed automatically whenever cin is
used
14Dissection of Example Program (contd)
Interactive Input Using cin Statement (contd)
- Consider following program
- include ltiostream.hgt
- int main()
-
- int score1 float score2
- cout ltlt "Enter value for score1 " ltlt endl
- cin gtgt score1
- cout ltlt "Enter value for score2 " ltlt endl
- cin gtgt score2
- return(0)
-
- What happens when, in response to the prompts,
- 98.5 followed by 78 are entered ?
- 98 followed by 78 are entered ?
15Dissection of Example Program (contd)
Interactive Input Using cin Statement (contd)
- Reading Character/String Data
- When reading character data using cin, keep mind
that - Only one character is read each time
- White spaces (spaces, tabs, newlines, etc.) are
ignored by cin when using the gtgt operator - check out get( ) function (page 279 of
textbook) - syntax cin.get( char_variable )
- Numeric values can be read as characters - each
digit is read as separate character - Difficulties will also arise when one tries to
use cin with the gtgt operator to read string
data - Check out functions like getline( ) (page 397 of
textbook)
16Dissection of Example Program (contd)Digression
File Processing in C
- Need for File Processing
- Have seen how data/results can be interactively
input/output (from/to standard input/output
device) - cin cout - Often times data/results must be written to or
read from secondary storage devices (disks) for
sharing between users/programs - Future assignments of this class, for example,
- Will need to use my data to test your programs
- Will need to write results to file to allow
viewing/printing - Need to know how to process (text) files in C
- Declaring, initializing closing file stream
(fstream) objects - Reading from files using fstream objects
- Writing to files using fstream objects
17Dissection of Example Program (contd)Digression
File Processing in C (contd)
- Declaring File Stream (fstream) Objects
- For C program to read values from file, an
ifstream (input file stream) object must first
be constructed (declared) to serve as connection
from file to program - Syntax ifstream InputStreamName
- Example ifstream inputStream1
- Similarly, for C program to write values to
file, an ofstream (output file stream) object
must first be constructed (declared) - Syntax ofstream OutputStreamName
- Example ofstream outputStream1
- ifstream ofstream classes are declared in
fstream library - fstream.h header file must be included to use
library - After fstream (ifstream or ofstream) object is
constructed, various operations can then be
applied to it (will see)
18Dissection of Example Program (contd)
Digression File Processing in C (contd)
- Initializing File Stream Objects
- fstream objects are uninitialized when declared
(constructed) - They serve as potential connections between
program files - Actual connections are made using open( )
member function - Syntax fstream_name.open ( file_name , mode )
- fstream_name is name of fstream object to be
initialized - file_name is name (character string) of file
- mode is optional argument indicating how file is
to be opened - Example inputStream1.open("in.dat", iosin)
- inputStream1 is ifstream object previously
declared - in.dat is name of file - as character string
- iosin specifies how file is to be opened (more
on this next)
19Dissection of Example Program (contd)
Digression File Processing in C (contd)
- fstream Modes (not an exhaustive list)
- Mode Description
- iosin Open file for input, nondestructively,
with read position - at files beginning. Default mode for
ifstream objects. - iosout Open file for output, destructively.
Default mode for - ofstream objects.
- iosapp Open file for output,
nondestructively, with write position - at files end (I.e., for appending)
- iosate Open existing file with read position
(if ifstream object) - or write position (if ofstream object) at end
of file - iosbinary Open file in binary mode
20Dissection of Example Program (contd)Digression
File Processing in C (contd)
- Initializing fstream Objects at Declaration
- C allows initializing an fsteam object when it
is declared - ifstream inputStream1("in.dat", iosin)
- is equivalent to
- ifstream inputStream1
- inputStream1.open("in.dat", iosin)
- This is similar to initializing a variable at
declaration such as - int total 0
- For this reason, open( ) member function is
rarely used in practice
21Dissection of Example Program (contd)Digression
File Processing in C (contd)
- Testing Success of File Opening
- File opening operation may fail for some reasons
- If so, any subsequent read or write attempts to
that file will also fail - Thus, success in opening file should always be
tested - Sample code segment
- if ( fstream_name.fail() )
-
- cerr ltlt "Error opening " ltlt file_name ltlt endl
- exit(1)
-
- fstream_name is name of fstream object for which
connection to file named file_name has been
attempted
22Dissection of Example Program (contd)Digression
File Processing in C (contd)
- Closing fstream Objects
- Syntax fstream_name.close( )
- Two things accomplished
- Executing program data file (that have been
connected through fstream object named
fstream_name) are disconnected - fstream_name becomes undefined
- Example
- inputStream1.close()
- Good programming practice to close (disconnect)
fstream objects explicitly when they are no
longer needed - Important when program uses many files -
operating system usually has limits on of files
program may have open simultaneously
23Dissection of Example Program (contd)Digression
File Processing in C (contd)
- Reading from/Writing to fstream Objects
- Reading using input operator (gtgt)
- Consistent with extraction operator used in
interactive input (cin) - Example
- inputStream1 gtgt Reading
- Writing using output operator (ltlt)
- Consistent with insertion operator used in
interactive output (cout) - Example
- outputStream1 ltlt "Average " ltlt Avg ltlt ".\n"
24Dissection of Example Program (contd)Digression
File Processing in C (contd)
- Two Other Items of Interest
- eof( )
- inputStream1.get(reading)
- while ( !inputStream1.eof() )
-
- // some desired processing statements here
- inputStream1.get(reading)
-
- getline( )
- Reads characters from fstream object, storing
them in string object, until newline character is
read - Newline character not stored in string object
25Learning by Example Dissection of Example
Program (contd)
- / Example program computes prints users age
in days - Course CS 2308-xxx Author ...
Date ... - ... /
- include ltiostream.hgt
- int main(void)
-
- const int DAYS_PER_YEAR 365 // constant
declaration - int ageInYears, ageInDays // variable
declarations - cout ltlt "Enter your age in years (whole
number) " - cin gtgt ageInYears
- ageInDays ageInYears DAYS_PER_YEAR
- cout ltlt "Your age is about " ltlt ageInDays ltlt "
days.\n" - return(0)
26Learning by Example Dissection of Example
Program
- The return Statement
- Allows executing function to directly return
value to calling function - Only one value can be returned using the
statement - Syntax
- return expression
- Examples
- return (0)
- return (x y z)
- return ( sin(alpha) cos(beta) )