Interactive Output in C Example Program - PowerPoint PPT Presentation

1 / 30
About This Presentation
Title:

Interactive Output in C Example Program

Description:

printf ( control-string , argument1 , argument2 , ... constants (e.g., 100, C', 'a string' - string constants in C) variables (e.g., days, years - in example program) ... – PowerPoint PPT presentation

Number of Views:202
Avg rating:3.0/5.0
Slides: 31
Provided by: myn91
Category:

less

Transcript and Presenter's Notes

Title: Interactive Output in C Example Program


1
Interactive Output in C Example Program
  • / Example program computes prints users age
    in days
  • Course CS 2308-252/253, Spring 1998
  • Author ...
  • Date ... /
  • include ltstdio.hgt
  • int main()
  • int years, days
  • printf("How old are you in years?\n")
  • scanf("d", years)
  • days years 365
  • printf("Your age is about d days\n", days)
  • return(0)

2
Interactive Output in C printf Function
  • Allows writing output to computers standard
    output device (usually the monitor or terminal)
  • One of many functions provided in C standard
    library
  • Declared in standard library header file stdio.h,
    which must be included
  • General format
  • printf ( control-string , argument1 , argument2 ,
    ... )
  • control string - string containing formatting
    info
  • arguments - represent individual output items

3
Interactive Output in C printf Function (contd)
  • Control String
  • Delimited by double quotes, which is how C
    recognizes strings
  • Composed of individual groups of characters -
    each character group begin with
  • Each character group specifies output format for
    each output item - they correspond in the order
    in which they appear
  • Character group (formally called conversion
    control sequence)
  • Simplest form - followed by a conversion
    character indicating data type of corresponding
    output item (e.g., d)
  • Character groups can be contiguous or separated
    by other characters (including spaces) - other
    characters (if any) are simply transferred
    directly to output device

4
Interactive Output in C printf Function (contd)
  • Some Commonly Used Conversion Characters
  • Conversion
  • Character Meaning
  • c display as character
  • d display as decimal integer
  • e display as floating-point with exponent
  • f display as floating-point with no exponent
  • s display as string

5
Interactive Output in C printf Function (contd)
  • Arguments (Output Items)
  • Can be written as
  • constants (e.g., 100, C, a string - string
    constants in C)
  • variables (e.g., days, years - in example
    program)
  • expressions (e.g., years365 - could have been
    used in place of years in 2nd printf statement in
    example program)
  • function references (e.g. sqrt(5) - needs
    math.h)
  • Type compatibility between argument (output item)
    conversion control sequence - your
    responsibility
  • printf("d, f\n", 1, 1) - whats wrong? how
    should it be?

6
Interactive Output in C printf Function (contd)
  • More Examples
  • printf("How old are you in years?\n")
  • printf("Your age is about d days\n", days)
  • printf("\nYou are d years (about d days)
    old\n",
  • years, days)
  • printf("Bytes allocated to char is d\n",
    sizeof(char))
  • printf("Bytes allocated to int is d\n",
    sizeof(int))
  • printf("Bytes allocated to float is d\n",
    sizeof(float))
  • printf("c d e f s\n", '1', 1, 1.0, 1.0, "1")

7
Interactive Output in C printf Function (contd)
  • More Examples (Formatted Output)
  • Additional formatting characters can be placed
    between and conversion character
  • Examples - only a taste of some of the flavors
  • printf("Sum of3d and4d is5d.", 6, 5, 21)
  • Sum of 6 and 15 is 21.
  • printf("-10d", 59) / left justified /
  • 59
  • printf("10d", 59) / signed /
  • 59
  • printf("-10d", 59) / signed left
    justified /
  • 59
  • printf("5.2f", 1234.6789) / whats the deal?
    /
  • 1234.67

8
Interactive Input in C scanf Function
  • / Example program computes prints users age
    in days
  • Course CS 2308-001
  • Author ...
  • Date ... /
  • include ltstdio.hgt
  • int main()
  • int years, days
  • printf("How old are you in years?\n")
  • scanf("d", years)
  • days years 365
  • printf("Your age is about d days\n", days)
  • return(0)

9
Interactive Input in C scanf Function (contd)
  • Allows input data to be entered into computer
    from standard input device (usually monitor or
    terminal)
  • One of many functions provided in C standard
    library
  • Declared in standard library header file stdio.h,
    which must be included
  • General format
  • scanf ( control-string, argument1, argument2,
    ... )
  • control string string containing formatting info
  • arguments represent individual input data items
    - actually addresses of where items are stored
    in computers memory

10
Interactive Input in C scanf Function (contd)
  • scanf("d", years)
  • Puts computer into wait state for as long as it
    takes user to enter data
  • User signals end of data entry by pressing
    Enter/Return
  • Entered value is stored in variable years, whose
    address was passed to scanf, computer is taken
    out of wait state
  • Program execution continues with the next
    statement
  • Another example scanf("f f", num1, num2)
  • entering 0.3 3.1 would result in 0.3 and 3.1
    being stored in num1 and num2, respectively
  • spaces between values matter only if char
    variable is involved

11
File Input/Output in C
  • Declaring Files
  • Within a C program, a file is always referenced
    by a variable name that must be declared within
    the program (like any other variables)
  • For files, the variable is actually a pointer to
    a special file structure
  • Syntax FILE file-pointer-name
  • Example FILE inputFilePtr
  • inputFilePtr is pointer name selected by you -
    name you want to use in your program to reference
    the file - need not be the same as the external
    name of the file
  • FILE is tag name of a special data structure used
    by C (declared in stdio.h, which must be
    included) for storing information about the file
  • Declaration for file variable follows the same
    format as for pointer variables

12
File Input/Output in C
  • Opening Files
  • Two things to accomplish
  • Establish physical communication link between
    program file
  • Equate files external name (used by
    computer/operating system) to files pointer name
    you want to use internally in your program
  • Accomplished using fopen - one of standard C
    library functions - declared in stdio.h, which
    must be included in the program
  • Syntax file-pointer-name fopen (external-name
    , desired-mode)
  • Example inputFilePtr fopen (
    "c\work\input.dat" , "r" )
  • inputFilePtr is pointer name for file previously
    declared
  • c\work\input.dat is path name of external
    file - as string
  • r is mode in which file is to be used - as
    string - more next

13
File Input/Output in C
  • File Modes (by no means exhaustive)
  • Mode Meaning existing or new? how will it be
    used?
  • r Existing file, to read - specified external
    file must exist
  • w New file, to write - if specified external
    file exists, it will be destroyed new file
    created in its place
  • a Existing file, to append (add new stuff at
    the end) - if specified external file doesnt
    exist, new file is created
  • r Existing file, to read write - specified
    external file must exist
  • w New file, to read write - if specified
    external file exists, it will be destroyed
    new file created in its place
  • a Existing file, to read append - if
    specified external file doesnt exist, new file
    is created

14
File Input/Output in C
  • Test for Successful File Opening
  • include ltstdio.hgt
  • include ltstdlib.hgt
  • int main()
  • FILE inFilePtr
  • char inFileName21
  • printf("\nEnter file name (up to 20
    characters) ")
  • gets(inFileName)
  • inFilePtr fopen(inFileName, "r")
  • if (inFilePtr NULL)
  • printf("\nError opening file s!",
    inFileName)
  • exit(1)
  • ...

15
File Input/Output in C
  • Test for Successful File Opening
  • include ltstdio.hgt
  • include ltstdlib.hgt
  • int main()
  • FILE inFilePtr
  • char inFileName21
  • printf("\nEnter file name (up to 20
    characters) ")
  • gets(inFileName)
  • if ( (inFilePtr fopen(inFileName, "r"))
    NULL )
  • printf("\nError opening file s!",
    inFileName)
  • exit(1)
  • ...

16
File Input/Output in C
  • Closing Files
  • Two things to accomplish
  • Break link between file's external internal
    names
  • Release internal file pointer name - can then
    be re-used
  • Accomplished using fclose - one of standard C
    library functions - declared in stdio.h, which
    must be included in the program
  • Syntax fclose ( file-pointer-name )
  • Example fclose ( inputFilePtr )
  • inputFilePtr is pointer name of file you want to
    close
  • All computers have limit on number of files that
    can be opened at one time - closing files that
    you no longer need makes good sense
  • All opened files are automatically closed by
    operating system upon normal termination of
    program

17
File Input/Output in C
  • Reading Writing Files
  • Files must be open before reading /or writing
  • Involve standard library functions similar to
    scanf printf
  • With addition of file (pointer) name to indicate
    the file from which to read or to which to write
  • Syntax
  • fscanf ( file-pointer-name, control-string,
    argument1, argument2, ... )
  • fprintf ( file-pointer-name, control-string,
    argument1, argument2, ... )
  • Arguments for fscanf must be addresses (same as
    for scanf )
  • E.g. fscanf ( inputFilePtr, "d f", intVar,
    floatVar )
  • E.g. fprintf ( outputFilePtr, "You are d days
    old.\n", days )
  • Must know how data appears in file to correctly
    read into variables

18
Dynamic Memory Allocation in C
  • Two functions that can be used for dynamic memory
    allocation in C (needs stdlib.h) malloc
    free
  • malloc
  • Reserves requested number of bytes as indicated
    by argument passed to it
  • Returns address of first reserved location or
    NULL if sufficient memory is not available
  • free
  • Releases block of bytes previously reserved
    (through malloc)
  • Receives address of first reserved location as
    argument

19
Dynamic Memory Allocation in C
  • In requesting storage space to be allocated using
    malloc, user must indicate amount of storage
    needed
  • One may specify specific number of bytes
  • More usually, one would request enough space for
    particular data type using sizeof operator
  • For example,
  • malloc(10 sizeof(int))
  • requests enough memory to store 10 integers
  • Address (of first byte of storage reserved)
    returned is declared (in stdlib.h) as pointer to
    void, regardless of data type requested
  • Returned address must always be reinterpreted
    (re-cast) as pointer to desired data type (will
    see how this is done)

20
Dynamic Memory Allocation in C Example
  • include ltstdio.hgt
  • include ltstdlib.hgt
  • int main()
  • int i, num, grades
  • printf("\nNumber of grades ")
  • scanf("d", num)
  • grades (int ) malloc(num sizeof(int))
  • if (grades NULL)
  • printf("\nFailed to allocate grades
    array.\n")
  • exit(1)
  • (Continued)

21
Dynamic Memory Allocation in C Example (contd)
  • for (i 0 i lt num i)
  • printf("Enter a grade ")
  • scanf("d", gradesi)
  • printf("\nAn array was created for d
    integers", num)
  • printf("\nValues stored in the array are\n")
  • for (i 0 i lt num i)
  • printf(" d\n", gradesi)
  • free(grades)
  • return(0)

22
Command Line Arguments
  • In C/C, arguments can be passed to any function
  • Have seen how arguments are passed to functions
    other than main
  • Arguments passed to main are called command
    line arguments
  • Common uses of command line arguments
  • Printing the arguments
  • Passing options to program
  • Passing filenames to program
  • Example program tcopy that copies one file
    called in into another file called out one
    character at a time
  • tcopy in out

23
Command Line Arguments
  • include ltstdio.hgt
  • int main(int argc, char argv)
  • FILE inFilePtr, outFilePtr
  • char c
  • if (argc ! 3)
  • printf("Usage tcopy infile outfile\n")
  • else
  • if ((inFilePtr fopen(argv1, "r")) !
    NULL)
  • if ((outFilePtr fopen(argv2, "w"))
    ! NULL)
  • while ((c fgetc(inFilePtr)) ! EOF)
  • fputc(c, outFilePtr)
  • else
  • printf("File s could not be
    opened\n", argv2)
  • else
  • printf("File s could not be opened\n",
    argv1)
  • return(0)

24
Command Line Arguments
  • include ltiostream.hgt
  • include ltfstream.hgt
  • int main(int argc, char argv)
  • char c
  • if (argc ! 3)
  • cout ltlt "Usage tcopy infile outfile\n"
  • else
  • ifstream inStream(argv1, iosin)
  • ofstream outStream(argv2, iosout)
  • if (!(inStream.fail()))
  • if (!(outStream.fail()))
  • while ( (c inStream.get()) ! EOF)
  • outStream.put(c)
  • else
  • cout ltlt "Error opening file " ltlt
    argv2
  • else
  • cout ltlt "Error opening file " ltlt
    argv1

25
Command Line Arguments
  • Command line indicates that file in is to be
    copied into file out
  • When program is run
  • If argc is not 3 (notice that tcopy counts
    as one argument), program prints error message
    terminates
  • Otherwise, array argv contains strings "tcopy",
    "in", "out"
  • 2nd argument in 3rd argument out on
    command line are used as file names by program
  • Files are opened using usual methods in C or in
    C
  • If both files are opened successfully, characters
    are read from file in written to file out
    until EOF for file in is reached
  • Copying is then successfully completed program
    terminates

26
Command Line Arguments
  • Command line tcopy in out
  • Upon encountering command line, operating system
    stores it as sequence of three strings as shown
    below, assuming each character used one byte of
    storage

t
c
o
p
y
\0
i
n
\0
o
u
t
\0
27
Command Line Arguments
  • Arguments passed to main, like all function
    arguments, must be declared as part of function
    definition
  • To standardize argument passing to main, only
    two items are allowed a number an array
  • The number is an integer variable, which must be
    named argc (short for argument counter),
    holds the total number of items on the command
    line (3 in our tcopy example)
  • The array is a 1D array, which must be named
    argv (short for argument values), holds a list
    of pointers containing the starting addresses of
    each string typed on command line

28
Command Line Arguments
integer
argv0
argc
argv1
argv2
arrayofpointers
t
c
o
p
y
\0
i
n
\0
o
u
t
\0
29
Command Line Arguments
  • include ltiostream.hgt
  • include ltstdlib.hgt
  • int main(int argc, char argv)
  • int sum0, count
  • cout ltlt "This program computes and displays
    the sum of 2 or more "
  • ltlt "integers you entered after the
    command line." ltlt endl
  • if (argc lt 3)
  • cerr ltlt "Usage command integer1 integer2
    ..." ltlt endl
  • else
  • for (count 1 count lt argc count)
  • sum atoi(argvcount)
  • cout ltlt "The sum of "
  • for (count 1 count lt argc count)
  • cout ltlt argvcount ltlt " "
  • cout ltlt "is " ltlt sum ltlt endl
  • return(0)

30
Command Line Arguments
  • include ltiostream.hgt
  • include ltstdlib.hgt
  • include ltstring.hgt
  • int main(int argc, char argv)
  • cout ltlt "This program converts (C to F or F to
    C) "
  • ltlt "a temperature given at command line."
    ltlt endl
  • if (argc lt 3)
  • cerr ltlt "Usage command option temperature"
    ltlt endl
  • ltlt " where option can be -C2F or
    -F2C" ltlt endl
  • else
  • if (!strcmp(argv1, "-c2f")
    !strcmp(argv1, "-C2F"))
  • cout ltlt argv2 ltlt " degrees C is "
  • ltlt atoi(argv2)9/5 32 ltlt "
    degrees F" ltlt endl
  • else if (!strcmp(argv1, "-f2c")
    !strcmp(argv1, "-F2C"))
  • cout ltlt argv2 ltlt " degrees F is "
  • ltlt (atoi(argv2) - 32)5/9 ltlt "
    degrees C" ltlt endl
  • else
Write a Comment
User Comments (0)
About PowerShow.com