Programming Fundamentals II
Programming Fundamentals II CSCI 152
Popular in Course
Popular in ComputerScienence
This 10 page Class Notes was uploaded by Janiya Renner MD on Friday October 30, 2015. The Class Notes belongs to CSCI 152 at Texas A&M University - Commerce taught by Sandra Huerter in Fall. Since its upload, it has received 64 views. For similar materials see /class/232405/csci-152-texas-a-m-university-commerce in ComputerScienence at Texas A&M University - Commerce.
Reviews for Programming Fundamentals II
Report this Material
What is Karma?
Karma is the currency of StudySoup.
Date Created: 10/30/15
CSCI 152 C INPUT AND OUTPUT WITH USERDEFINED TEXT FILES To read from or write to a text file in C the header file fstreamh must be included fstreamh includes the definitions for the stream classes ifstream for input from a user defined file ofstream for output to a user defined file fstream for input to and output from a user defined file and iostream for interactive IO All the functions operators and manipulators previously discussed for interactive IO can be applied to user defined files streams as well they work in the same way Examples ifstream inFile declare input le or ifstream inFile quotcdatainfiletxtquot declare and open input le ofstream outFile declare output le or ofstream outFile quotreporttxtquot declare and open output le If you declare a file object but do not specify a filename for the stream with which it is to be associated you may explicitly open the file using the open function which requires as parameters the name of the file to be opened and optionally the mode in which the file will be accessed For example ifstream inFile ofstream outFile inFileopen quotaprogldatquot outFileopen quotproglrptquot Variable filenames You can use a variable for the filename which allows you to read in the filename and then open the file The trick is that the open function requires an old C style string rather than the new string type ifstream myFile or string filename char filename 81 cout ltlt quotEnter input file name quot cout ltlt quotEnter input file name quot cin gtgt filename cin gtgt filename ifstream myFilefilenamedata myFileopen filename Closing files All files are automatically closed when they pass out of scope or at the end of the program but you may explicitly close a file at any time by calling the close function Example inFileclose outFileclose Checking for FileRelated Errors File related errors are typically caused by not being able to locate and open a file usually because the filename given in the program is spelled incorrectly or the file is not located where the program expects to find it Another typical error is caused by attempting to read your data in the wrong sequence Suppose we have these declarations int n k double X char ch and we have this line of data in the file myFiIe A 42 314 Assume the same data is read by each of these possible statements in a program myFiIe gtgt ch gtgtngtgt x ch A n42 x314 myFile gtgt ch gtgt X gtgt n ch A X 420 n 3 14 is waiting to be read myFiIe gtgt ch gtgt n gtgt k gtgt X ch A n 42 k 3 X 14 Notice in the last statement that the single input value 314 is split between two variables the 3 is read for k and the 14 is read for X This may not be what we meant to do but it does not cause an error except perhaps a logic error when we get the wrong answer But what if nothing at all can be input for a variable because the value to be read is not compatible with the type myFile gtgt n gtgt X gtgt ch A can t be read for an int or double variable myFiIe gtgt ch gtgt X gtgt k gtgt n ch A X 420 k 3 but we can t read a decimal point for a value for n Both of the last two statements cause input failure Nothing more can be read from this file any other input statements that might appear in the program following those statements will be ignored Your program can test for this problem and take action to clear the problem and allow input to continue if myFilefail or if myFile myFileclear myFileclear The state of a stream may be tested by using functions to access a collection of bits represented by enumerated values in the class ios Name Bit is set if ios good bit all other bits are off good condition ios eofbit end of file is detected also sets failbit ios failbit last input operation failed but no data lost recoverable error For example a char was encountered when trying to read a numeric value ios bad bit invalid operation attempted with possible loss of data unrecoverable error ios hardfail an unrecoverable error occurs The functions used to access these bits are Function Description good Returns true if eof fail and bad would all return zero false eof Returns true if eofbit is on fail Returns true if failbit badbit or hardfail is on bad Returns true if bad bit or hardfail is on clear Restores stream39s state to good clears error status so you can retry 10 The ifstream class returns 0 if the end of file condition is reached 50 any of the following could be used to test for end of file while inFile while inFileeof while inFilefail though fail returns true for reasons other than end of le However in actual practice the eofbit doesn39t seem to get set until an attempt is made to read past the end of file marker so using the eof function to test for end of file can be problematic What usually happens is that the loop doesn t stop when you want it to but tries to read another line of data It then actually finds the eof marker and does set the eofbit But before it can test again to exit from the loop it has to go through the rest of your processing usually that means an extra line of output as it processes the last line of data again That can also mess up the values of any totals or counts you were keeping See the next two pages for examples of possible ways to terminate an end of file processing loop Partial sample program demonstrating user defined text file handling include ltfstreamgt Prototypes for le stream functions include ltiomanipgt Prototypes for IO formatting functions include ltcstdlibgt Prototype for exitand system include ltcassertgt Prototype for assert using namespace std int main int userid string lastName float salary ofstream rptFile ifstream dataFile quotadatafiletxtquot Declare an input le locally and open it rptFileopen quotareporttxtquot Open output le Check to be sure le is open if dataFilefail or if dataFile or if dataFile 0 cout ltlt quotCannot open input filenquot exit 1 exit function terminates program but you can do something rst like print a message or assert dataFile Program terminated immediately if le can39t be opened cout ltlt fixed ltlt showpoint Float numbers will be output to screen and le in rptFile ltlt fixed ltlt showpoint decimal notation All float values will be printed with a decimal point even if the fractional part is zero Read and Process one line of data while dataFilepeek EOF peek gives a copy of the next char to be read EOF is a constant for the end of le marker dataFile gtgt userid gtgt lastName gtgt salary read one line of input data echo the input to check that the program is reading the data correctly cout ltlt quotuserid quot ltlt userId ltlt 39 39 ltlt lastName ltlt 39 39 ltlt setprecision2 ltlt salary ltlt endl dataFileignore 1 n or dataFileget to get rid ofnewline process the input data do whatever you need to do for your application rptFile ltlt userId ltlt left ltlt setw 13 ltlt lastName ltlt right ltlt setprecision2 ltlt setw 10 ltlt salary ltlt endl end of loop to process one customer system quotpausequot return 0 Normal end of program end of function main Alternate methods for detecting endoffile Version 1 astName gtgt 5 al e gtgt operator returns 0 false if while dataFile gtgt userid gtgt 1 ar Th no data is read or returns a nonzero true Valu otherwise you won t enter loop if there is no more data dataFileignore 1 n or dataFileget to get rid of newline Process the input data l end of loop to process one person Version2 while dataFileeof dat aFi e gtgt useri 01 gtgt last Name gtgt salary if dataFileeof Check again for end of file after trying to read break Gjarantee exit fromoop at end of file dataFi le ignore 1 n or dataFi e get to get rid of newline Process the input data end of loop to process one person Version 3 dataFile gtgt userid Read the first data Value on a line of data while l dataFileeOf or While dataFile or while l dataFilefail dataFile gtgt lastName gtgt salary read the rest of the data line dataFileignore l n or dataFileget to get rid of newline Process the input data dataFile gtgt userid Try to read next id end of loop to process one person In applications where input is read one character at a time this method could also be used Version 4 int ch Note the declaration as int rather than char The endeofefile marker is typically represented as fl which cannot be stored in a char Variable while ch dataFileget l EOF read a char and check to see if we ve read the endeofefile marker Process the input character or ch dataFileget or dataFilegetch to read the first character while ch l EOF Process the input charac er ch dataFileget or dataFilegetch to read the next character l CSCI 152 C INTERACTIVE INPUT AND OUTPUT Output The insertion operator ltlt is used for general output of values of multiple types It has been defined to output values in a default format for all of the builtin basic C types Because ofthe way the operator is defined it is possible to output multiple values in the same statement by chaining them together with the ltlt insertion operator cout ltlt valuel ltlt valueZ is thesarneas cout ltlt valuel cout ltlt valueZ where the variables or constants or expressions may be of any ofthe builtn basic types The insertion operator converts values to text form By default values are displayed in a width equal to their size and formatted as follows char A type char value if it represents a printable character is displayed as a character in a field one character wide int Numeric integer types are displayed as decimal integers in a field just wide enough to hold the number and ifthe value is negative a minus sign float Floatingpoint types are displayed with 6 places to the right ofthe decimal except that trailing fractional zeros aren39t displayed lfthere are no significant digits to the right ofthe decimal point printing ofthe decimal point is suppressed along with the trailing zeros The number may be displayed in Enotation depending upon the value ofthe number which depends on the implementation being used Again the field is just wide enough to hold the number and for a negative value a minus sign string Strings are displayed in a field width equal in width to the length of the string Examples of default field widths these defaults may vary from one compiler to another 1 i ncl ude lti ost reamgt 2 using nanespace std 3 int nai n value displayed 4 cout ltlt 3939 ltlt quotIm1701quot ltlt quotnquot Nm1701 5 char ch39K39 intt273 6 cout ltlt 3939 ltlt ch ltlt quotnquot K 7 cout ltlt 3939 ltlt t ltlt quotnquot 273 8 cout ltlt 3939 ltlt t ltlt quotnquot 273 9 double f1 1200 10 cout ltlt 3939 ltlt f1 ltlt quotnquot 12 11 cout ltlt 3939 ltlt f1 10 90 ltlt quotnquot 1311111 12 double f2 16E7 13 cout ltlt 3939 ltlt f2 ltlt quotnquot 16000000 14 cout ltlt 3939 ltlt f2 10 90 ltlt quotnquot 16000000111111 15 cout ltlt 3939 ltlt f2 2 0e5 ltlt quotnquot 162e07 16 float f3 2 3e4 cout ltlt 3939 ltlt f3 ltlt quotnquot 0 00023 cout ltlt 3939 ltlt f3 10 ltlt quotnquot39 2 3e05 17 18 The pant where the defaut svw39tches fromfXed t0 scentfc 5 dependent 0n the carrpfer you use 19 float f450 20 cout ltlt 3939 ltlt f4 ltlt quotnquot 5 21 return 0 To override any of C39s default formatting C provides manipulators which have special meaning in the context of input andor output constructs Each causes a corresponding library function to be called which changes the state ofthe specified stream as requested To use any ofthese manipulators simply insert them within the lO stream preceding the value they are to manipulate Manipulators Having No Parameters defined in iostreamh Manipulator Purpose dec Sets the stream39s radix base to decimal default endl Inserts a newline and flushes the stream output only By default output streams are buffered so use flush or endl to write out immediately ends Inserts a null character output only flush Flushes the stream output only hex Sets the stream39s radix base to hexadecimal oct Sets the stream39s radix base to octal ws Skips leading white space on input default The following manipulators were added as part of the new ANSI standard boolalpha Causes boolean values to be inputoutput as strings true and false instead of 1 and 0 noboolalpha Causes boolean values to be inputoutput as integers 1 and 0 fixed Causes float values to be displayed in fixed decimal format scientific Displays float values in exponential notation internal Pads after sign or base indicator to fill specified field width left Causes output to be leftjustified right Causes output to be rightjustified default showbase Shows the base for octal 0 and hexadecimal Ox numbers noshowbase Does not show the base for hexadecimal and octal output showpoint Shows the decimal point and trailing zeros for float values noshowpoint Suppresses display of decimal point for float values with a zero fractional part Displays trailing zeros for float values with a nonzero fractional part showpos Adds leading to positive numbers noshowpos Does not show for positive numbers default skipws Skips leading whitespace on input default noskipws Does not skip leading whitespace on input unitbuf Flushes the output buffer after each insertion operation nounitbuf Does not flush output buffer after each insertion operation uppercase Shows hexadecimal numbers and exponent in uppercase nouppercase Displays hexadecimal numbers and exponents in lower case If your program includes the statement using namespace std the preceding manipulators may be inserted directly into the output stream Without the namespace statement they can only be used with the setiosflags and resetiosflags manipulators below See the sample program on p 3 for examples of using them in a program Manipulators Having One Parameter defined in iomaniph Manipulator Purpose setprecision int p Sets the number of digits displayed after a decimal point for floats affects output only ifthe fractional portion of the number is nonzero setw int w Sets field width for next output value only setiosflags long f Sets format state flags specified inf resetiosflags long f Turn off reset to default the format state flags specified inf setbase int base Sets number base to 8 10 or 16 default is 10 setfill int ch Sets fill character default is blank The generalpurpose manipulators setiosflags and resetiosflags have a parameter of a set of bitflags Each open stream maintains a series of bitflags Each flag records whether a particular attribute is or is not 2 set This set of flags records the stream39s format state In iostreamh an enumerated type is defined with a set of enumeration constant names for each format state Example of using manipulators 1 include ltiostreamgt or include ltiostreamhgt 2 include ltiomanipgt or include ltiomaniphgt 3 using namespace std 4 int main 5 cout ltlt setw10 ltlt 123 ltlt 12378 ltlt endl 6 cout ltlt 3939 ltlt setw8 ltlt setprecision3 ltlt 12378 ltlt 3939 ltlt endl 7 cout ltlt 3939 ltlt 15 ltlt 3939 ltlt 154321 ltlt 3939 ltlt endl 8 cout ltlt left ltlt 3939 ltlt setw4 ltlt setprecision2 ltlt 10 ltlt 3939 ltlt endl If not using namespace std you have to do it the old way cout ltlt setiosflagsios1eft ltlt 3939 ltlt setw4 ltlt setprecision2 39 ltlt endl 9 cout ltlt showpoint ltlt right If not using namespace std you have to do it the old way cout ltlt setiosflagsiosshowpoint ltlt setiosflagsiosright or cout ltlt setiosflagsiosshowpoint iosright39 or cout ltlt setiosflagsiosshowpoint ltlt resetiosflagsios1eft 1O cout ltlt 3939 ltlt setw8 ltlt 10 ltlt 3939 ltlt endl 11 cout ltlt setprecision1 ltlt fixed ltlt 3939 ltlt setw6 ltlt 1264 ltlt 3939 ltlt endl If not using namespace std you have to do it the old way cout ltlt setprecision1 ltlt setiosflagsiosfixed ltlt 3939 ltlt setw6 1264 ltlt 3939 ltlt endl 12 return 0 1234567890123456 column positions Output 12312378 1238 151543 1 A 100 13 Input The extraction operator gtgt is used for general input of values of multiple types The extraction operator is defined for all the builtin basic C types As with the insertion operator it is possible to input values for multiple variables in the same statement by chaining them together with the extraction operator cin gtgt valuel gtgt value2 is the same as cin gtgt valuel cin gtgt value2 To input a numeric value leading whitespace is skipped and then characters are input until a character inappropriate for the type is encountered The default input base is decimal numbers without an explicit base are assumed to be decimal but it is possible to input octal or hexadecimal values by explicitly entering the base 024 would be read as an octal 24 decimal 20 and 0x14 would be read as a hexadecimal 14 decimal 20 Leading whitespace is also skipped when characters and strings are input When a value is to be read for a char variable the first nonwhitespace character is input When a value is to be read for a string variable characters are read starting with the first nonwhitespace character until whitespace endofline blank tab endoffile is encountered Additional Functions for Specialized IIO defined in iostreamh istream amp get char amp c inputs the next character even if it is whitespace storing the input character in the char parameter This form ofthe function returns 0 false if end of file is encountered before a character can be input Example cin get ch int get void inputs the next character even if it is whitespace returning the character input or returning EOF if end of file EOF is a predefined constant for the endoffile symbol Example ch cinget or while Ch Cinget l 39n39 read chars across a line until the endof line marker is found Examples of reading chars until the endof line marker n is found assume the declaration char ch a b C cin gtgt ch cingetch whilech39n39 whilech39n39 Whilechcinget39n39 cout ltlt c cout ltlt ch cout ltlt ch cin gtgt ch cingetch Input for each program is the 7 characters H anI followed by the enter key n symbol Output for each program a b C Hi mm H me H me contnues n an nf nfe loop istream amp ignore int len 1 int delim EOF skips over a designated number of characters first parameter default is 1 or terminates upon encountering a designated delimiter second parameter default is EOF which causes ignore to skip to the end of file when reading from a file The delimiter is skipped Example cin ignore or cin ignore 2 or cin ignoreBO 39 n39 ostream amp put char c outputs one character the parameter supplied Example coutput 39 a39 make computerbeep or coutput 39A39 ostream amp put int n outputs the char equivalent ofthe parameter assumed to be an ASCII number Example coutput7 make computerbeep or coutput65 display A39 int peek void returns next character in the input stream but does not remove the character from the stream that character remains to be read Example ch cinpeek or while ch Cinpeek l 39 39 or while cinpeek 39n39 int eof void returns true if end of file has been reached or returns false otherwise Example While l cineof you d have to enter the endof e symbol from the keyboard for DOS it s Ctr Z for Mac and UNIXLinux it s Ctr D