CMPT 102 Introduction to Scientific Computer Programming. Input and Output. Your first program

Similar documents
C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

Advanced C Programming Topics

Standard File Pointers

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Input/Output: Advanced Concepts

Input / Output Functions

Fundamentals of Programming

Fundamental of Programming (C)

Unit 4. Input/Output Functions

CC112 Structured Programming

Formatted Input/Output

DATA STRUCTURES USING C

Binghamton University. CS-220 Spring Includes & Streams

AWK - PRETTY PRINTING

SAMPLE MIDTERM SOLUTION

C Concepts - I/O. Lecture 19 COP 3014 Fall November 29, 2017

Stream Model of I/O. Basic I/O in C

Should you know scanf and printf?

Introduction to Computing Lecture 03: Basic input / output operations

printf("%c\n", character); printf("%s\n", "This is a string"); printf("%s\n", string); printf("%s\n",stringptr); return 0;

CpSc 1111 Lab 4 Formatting and Flow Control

Course organization. Course introduction ( Week 1)

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

CpSc 111 Lab 3 Integer Variables, Mathematical Operations, & Redirection

ANSI C Programming Simple Programs

Week 3 More Formatted Input/Output; Arithmetic and Assignment Operators

INTRODUCTION TO C++ C FORMATTED INPUT/OUTPUT. Dept. of Electronic Engineering, NCHU. Original slides are from

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Standard C Library Functions

CMPT 102 Introduction to Scientific Computer Programming

C: How to Program. Week /Mar/05

SWEN-250 Personal SE. Introduction to C

Formatted Output Pearson Education, Inc. All rights reserved.

CpSc 1011 Lab 3 Integer Variables, Mathematical Operations, & Redirection

C Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach

ET156 Introduction to C Programming

Input/Output Week 5:Lesson 16.1

Binghamton University. CS-211 Fall Input and Output. Streams and Stream IO

Chapter 2 - Introduction to C Programming

File IO and command line input CSE 2451

Organization of a file

Fundamentals of Programming. Lecture 11: C Characters and Strings

Programming in C. Session 2. Seema Sirpal Delhi University Computer Centre

2. Numbers In, Numbers Out

1/25/2018. ECE 220: Computer Systems & Programming. Write Output Using printf. Use Backslash to Include Special ASCII Characters

Getting started with Java

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12

Basic I/O. COSC Software Tools. Streams. Standard I/O. Standard I/O. Formatted Output

211: Computer Architecture Summer 2016

Integer Representation. Variables. Real Representation. Integer Overflow/Underflow

Operators and Control Flow. CS449 Fall 2017

Binghamton University. CS-211 Fall Input and Output. Streams and Stream IO

Chapter 5. Section 5.1 Introduction to Strings. CS 50 Hathairat Rattanasook

CPE 101, reusing/mod slides from a UW course (used by permission) Lecture 5: Input and Output (I/O)

Computer System and programming in C

CYSE 411/AIT681 Secure Software Engineering Topic #12. Secure Coding: Formatted Output

2/9/18. CYSE 411/AIT681 Secure Software Engineering. Readings. Secure Coding. This lecture: String management Pointer Subterfuge

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

UNIT IV-2. The I/O library functions can be classified into two broad categories:

Number Systems, Scalar Types, and Input and Output

EE458 - Embedded Systems Lecture 4 Embedded Devel.

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Programming for Engineers Introduction to C

THE FUNDAMENTAL DATA TYPES

Week 2 C Fundamentals; Formatted Input/Output; int and float Types

Basic Types and Formatted I/O

C Basics And Concepts Input And Output

2. Numbers In, Numbers Out

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

File I/O. Arash Rafiey. November 7, 2017

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

Programming in C. Session 8. Seema Sirpal Delhi University Computer Centre

Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance. John Edgar 2

LSN 3 C Concepts for OS Programming

Goals of C "" The Goals of C (cont.) "" Goals of this Lecture"" The Design of C: A Rational Reconstruction"

Fundamentals of Programming Session 4

Console Input and Output

EC 413 Computer Organization

Formatting functions in C Language

Chapter 10: File Input / Output

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Introduction to C An overview of the programming language C, syntax, data types and input/output

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

CSCI 2132: Software Development. Norbert Zeh. Faculty of Computer Science Dalhousie University. Introduction to C. Winter 2019

Lecture 3. More About C

File Handling in C. EECS 2031 Fall October 27, 2014

Full file at

EL2310 Scientific Programming

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Files and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060

Output with printf Input. from a file from a command arguments from the command read

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

These are reserved words of the C language. For example int, float, if, else, for, while etc.

C programming basics T3-1 -

Note: unless otherwise stated, the questions are with reference to the C Programming Language. You may use extra sheets if need be.

C Tutorial: Part 1. Dr. Charalampos C. Tsimenidis. Newcastle University School of Electrical and Electronic Engineering.

Transcription:

CMPT 102 Introduction to Scientific Computer Programming Input and Output Janice Regan, CMPT 102, Sept. 2006 0 Your first program /* My first C program */ /* make the computer print the string Hello world */ /* connect to any necessary libraries */ #include <stdio.h> /* the main function, implements the algorithm to solve the problem*/ /* the main function may use functions from included libraries */ int main ( ) { printf("hello, world!\n"); } Janice Regan, CMPT 102, Sept. 2006 1 1

General form for printf printf( format string, arg1, arg2,.); The format string (also called a control string) may contain text to be printed and conversion fields (instruction on how to print the values) The control string should have one conversion field for each argument to be printed. If there are too many conversion fields they are printed with unpredictable results If there are not enough conversion fields, the variables without conversion fields will be ignored Janice Regan, CMPT 102, Sept. 2006 2 printf: Writing results The format string contains text and conversions Text includes explanations you wish to include in your output, punctuation, and spaces Conversions are instructions giving the format to print each variable in the print statement. The contents of your format string will be printed on the output line Conversion fields will be replaced with the values of the indicated variables using the specified conversion. The conversion type is should be of the same type as the variable Janice Regan, CMPT 102, Sept. 2006 3 2

Example of printf statement /* Print the sum. */ printf("the sum is %12.2f ", sum); The %12.2f is the conversion, all other characters (including blanks) between the " " will be printed directly to the output line The %12.2f will be replaced by the value of the variable sum when it prints to the output line The variable sum will be printed with 2 digits after the decimal place, and using a total of at least 12 characters including the decimal place. If less than 12 digits (9digits decimal 2 digits) are needed the extra digits will be replaced by blanks Janice Regan, CMPT 102, Sept. 2006 4 Using the printf statement /* Print the sum. */ printf("the sum is %12.2f ", sum); To print 589.733 589.73 (number preceded by 6 blank spaces) To print 798765.987632 798765.99 (number preceded by 3 blank spaces) To print 4.58 *10 10 4580000000.00 (no preceding blank spaces) If it requires more digits to print the number than is provided by the conversion the number will be printed in the smallest number of digits possible consistent with the conversion, even if this number is larger than the value specified Janice Regan, CMPT 102, Sept. 2006 5 3

Conversions for printf: 1 A % to indicate the start of the conversion field An optional flag field which may contain left justify + prepend + or space negative numbers printed with a preceding positive numbers printed with a preceding blank ) An optional number indicating minimum field width to be printed (minimum # of characters reserved) An optional period separating the field width from the precision ( not present for integer types) A optional number indicating the precision or the number of digits displayed after the decimal in a floating point number Janice Regan, CMPT 102, Sept. 2006 6 Conversions for printf: 2 An h or an l indicating short or long A conversion character d, i, u for integers and unsigned integers f for doubles and floats, c for characters e for exponential format floating point number g for general format, if exponent is <-4 or greater than the precision uses e otherwise uses f Note: to print a % to your output you must put %% in your format statement Janice Regan, CMPT 102, Sept. 2006 7 4

Special characters in printf statements There are other strings of characters, called escape sequences, you can place within your format statement to produce particular results \n newline: move to the next output line \b backspace: move back one space before printing the next character \t horizontal tab \v vertical tab \\ print a \ \? Print a? \" print a \ print a Note that a format statement should not contain the character produced by typing <enter> Janice Regan, CMPT 102, Sept. 2006 8 Printing Integers: Examples: 1 int int1 = 2468, int2 = 948472, int3 = -75; long int int4 = 286215790L; printf( "%d\n", int1); printf( "%d%d\n", int1, int2); printf( "%+d, %d, %-d, %-d\n", int1, int2, int3, int1); printf( "%8d, % d,\n %8d, %d\n", int1, int2, int3, int4); 2468 2468948472 +2468, 948472, -75, 2468 2468, 948472, -75, 286215790 Janice Regan, CMPT 102, Sept. 2006 9 5

Printing Integers: Examples: 2 Things to note from Printing Integers: Examples: 1 When there is no space between conversions, there are no spaces between the printed outputs. This is why second line of output looks like one number instead of two Anything you wish to appear in the output that is not the value of a variable must appear in the format statement The number of variables in the variable list must match the number of conversions in the format statement When we specify a minimum field width (like the 8 in the last printf statement) remember that the sign counts as a digit. When you want a new output line use a \n after the last thing (character or conversion) you want on the present line If you put a space after \n you will get a space at the beginning of the next line Remember the quotation marks around the format statement Janice Regan, CMPT 102, Sept. 2006 10 Printing Integers: Examples: 3 unsigned int int2 = 4294900000U, int1 = 12122468U; long int int3=-4567l, int4 = 2086215790L; printf( "%i, %i\n", int1, int2); printf( "%u, %u\n", int1, int2); printf( "%12d, %7d, %10d\n", int3, int3, int4); printf( "%-12d, %+7d, %+10d\n", int3, int3, int4); printf( "% 12d, % 7d, % 10d\n", int3, int3, int4); 12122468, -67296 12122468, 4294900000-4567, -4567, 2086215790-4567, -4567, +2086215790-4567, -4567, 2086215790 Janice Regan, CMPT 102, Sept. 2006 11 6

Printing Integers: Examples: 4 More things to note Printing from Examples %d and %i both print signed integers %u should be used to print unsigned integers. If %d or %i is used to print an unsigned integer then the correct integer may not be displayed If the unsigned integer is small enough to be represented as a signed integer of the same length the displayed integer will be the same ( as for 12122468 in the example) If the unsigned integer is too large, for example the integer 4294900000 in the example, then the number printed will not be the value of the unsigned integer An integer that is too large has a 1 in the most significant binary bit, the sign bit for a signed integer. The integer is displayed as a negative number (sign bit 1) rather than the larger unsigned integer. Janice Regan, CMPT 102, Sept. 2006 12 Printing Integers: Examples: 5 More things to note Printing from Examples The minimum width of a field can be specified The 7 in %7d A field 7 characters wide will be used to print the integer, the field will be padded (on the left) with blanks if necessary. The field may be wider than 7 characters if the number requires it Numbers can be left justified. The in %-12d This means any padding with blanks happens on the right rather than on the left. The number is printed with the first digit in the leftmost position You can choose to display + on a positive number and on a negative number (Use the + in %+7d or in %+12d ) You can leave a space for a sign, but display it only if it -. (Use the space as in % 7d ) Janice Regan, CMPT 102, Sept. 2006 13 7

Printing float and double variables float flt1 = 1.001, flt2 = 333.333330001, flt3 = -4.5E12; float flt4 = 66.54E-08; printf( "%f, %f, %f\n", flt1, flt2, flt3); printf( "%5.3f, %9.3f\n", flt1, flt2); printf( "%e, %+e, \n %8.4e, %+12.3e\n", flt3, flt4, flt3, flt4); printf( "%g, %g, %g, %g\n", flt1, flt2, flt3, flt4); 1.001000, 333.333344, -4500000079872.000000 1.001, 333.333-4.500000e+12, +6.654000e-07, -4.5000e+12, +6.654e-07 1.001, 333.333, -4.5e+12, 6.654e-07 Janice Regan, CMPT 102, Sept. 2006 14 Printing float and double variables 2 Float and double variables can be printed as decimal numbers mmmm.pppppp using the %f conversion the precision or the number of digits after the decimal point can be specified. If it is not specified it will default to 6. The.3 in %5.3f (3 digits follow the decimal point) is an example of specifying the precision The width of the field includes the decimal point and sign Float and double variables can also be printed in exponential form, mmmm.ppppppe±kk The precision works the same as for the decimal format The.4 in %8.4e (4 digits follow the decimal point) is an example of specifying the precision The width of the field includes the decimal point, the E, the sign and the sign and digits of the exponent Janice Regan, CMPT 102, Sept. 2006 15 8

Printing Long Double Numbers long double flt5 = 12345678.123456789L; printf( "%Lf\n ", flt5); printf( "%f\n ", flt5); printf( "%Le\n", flt5); printf( "%e\n", flt5); 12345678.123457-0.000000 1.234568e+07-7.504921e-18 l Janice Regan, CMPT 102, Sept. 2006 16 Print functions printf( format string, arg1, arg2, ); Prints to the standard output fprintf( file, format string, arg1, arg2,.); Prints to a file sprintf( buff, format string, arg1, arg2,.); Prints to a buffer Janice Regan, CMPT 102, Sept. 2006 17 9

General form for printf printf( format string, arg1, arg2,.); The format string (also called a control string) may contain text to be printed and conversion fields (instruction on how to print the values) The control string should have one conversion field for each argument to be printed. If there are too many conversion fields they are printed with unpredictable results If there are not enough conversion fields, the variables without conversion fields will be ignored Janice Regan, CMPT 102, Sept. 2006 18 Sending your output to a file printf sends your output to the standard output device, usually the monitor screen There are two approaches to sending output to a file Redirection of the output Writing output directly to the file using fprintf The second approach gives more flexibility You can write part of the output to a file and part to your screen (output to file, prompts to screen) You can write different parts of your output to different files (Summary output to one file, detailed output to another) fprintf requires that you identify the file the data is to be written into Janice Regan, CMPT 102, Sept. 2006 19 10

Redirection of output All information that would normally be written to the standard output (screen) will be written into file outfile instead./myprog > outfile File outfile will be created if it does not exist, then the output will be written into file outfile The command will fail if outfile already exists./myprog >> outfile File outfile will be created if it does not exist, then the output will be written into file outfile If file outfile already exists the output will be appended to the end of file outfile Janice Regan, CMPT 102, Sept. 2006 20 General form for printf fprintf( filep, format string, arg1, arg2,.); The format string (also called a control string) may contain text to be printed and conversion fields (instruction on how to print the values) The control string should have one conversion field for each argument to be printed. The filep identifies the file into which the data is to be written The file pointer, filep, has a special type. FILE The file pointer provides a reference to the desired file To associate the file pointer with the file, the file must be opened Janice Regan, CMPT 102, Sept. 2006 21 11

The fopen function To open any file we need to know If we will be reading from the file " r" If we will be writing to the file (overwriting existing contents of the file) "w" If we will be appending our output to the end of an existing file. "a The name (filepath) of the file we wish to ope filep = fopen("filename", "w") The value of the variable filep is of type FILE *, a reference to a file. The variable filep is used to reference the file once it has been opened. Janice Regan, CMPT 102, Sept. 2006 22 Using the fprintf statement: 1 When you declare variables you must also declare a variable of type FILE which will be used to reference the file within your program FILE * DataFileExp1 Before you can read data from a file you must open it using fopen DataFileExp1 = fopen("filename", "w"); This connects the variable DataFileExp1, known as a file pointer (it points to or references the file) to the file with name filename Janice Regan, CMPT 102, Sept. 2006 23 12

Using the fprintf statement: 2 Once the file is opened you can read data fprintf(datafileexp1, format string, arg1, ); This will write arguments arg1, (with the format specified in the format string) to the file pointed to by DataFileExp1 (filename). When you are finished writing to the file you must close the file filename fclose(datafileexp1); This assures that the last of your data is written into the file (not left in a buffer) Janice Regan, CMPT 102, Sept. 2006 24 Precision of representations in C short maximum: 32767 int maximum: 2147483647 long maximum: 2147483647 float precision digits: 6 float maximum exponent: 38 float maximum: 3.402823e+38 double precision digits: 15 double maximum exponent: 308 double maximum: 1.797693e+308 long precision digits: 18 long maximum exponent: 4932 long maximum: 1.189731e+4932 For the gcc compiler in cygwin Janice Regan, CMPT 102, Sept. 2006 25 13

General form for scanf scanf( format string, &arg1, &arg2,.); The format string contains characters and conversion fields for the variables to be read The format string should have one conversion field for each argument to be read. & is the unary address operator, it tells the computer to print the value read at the address reserved for the variable Janice Regan, CMPT 102, Sept. 2006 26 scanf: Reading results The format string contains text and conversions Text (not blanks or tabs or newlines) must match text in the input stream Conversions are instructions giving the format to read each variable in the read statement. The contents of your format string will be read from the standard input (usually the keyboard) scanf continues reading until all conversions in the format string have been used or until an end of file is received, or until a conflict occurs ( the next character does not match the identifier or the expected text) Janice Regan, CMPT 102, Sept. 2006 27 14

Conversions for scanf: 1 A % to indicate the start of the conversion field An optional assignment suppression character An optional number indicating maximum field width to be printed An h or an l indicating short or long A conversion character d, i, u for integers and unsigned integers e, f, g for doubles and float, c for characters, s for a string of characters Janice Regan, CMPT 102, Sept. 2006 28 scanf example Consider the input data stream: First test, the 1st input is 3.65, the 2nd is 234, the last is 1.234e-05 This can be read using scanf in the following ways: scanf( First a test, the 1st input is %4.2f, the 2nd is %3d, the last is %9e, &flvar1, &intvar2, &expvar3); scanf( %*s %*s %*s %*s %*s %*s %4f %*s %*s %*s %3d %*s %*s %*s %9e, &flvar1, &intvar2, &expvar3); scanf( %*31c %f %*11c %3d %12c %9e, &flvar1, &intvar2); Janice Regan, CMPT 102, Sept. 2006 29 15

read functions scanf( format string, arg1, arg2,.); Reads from the standard input Usually the keyboard fscanf( file, format string, arg1, arg2,.); Reads from a file sscanf( buff, format string, arg1, arg2,.); Reads from a buffer Janice Regan, CMPT 102, Sept. 2006 30 General form for fscanf fscanf(filep, format string, &arg1, &arg2,...); The filep ( type FILE) references or points to the file being read from The format string contains characters and conversion fields for the variables to be read The format string should have one conversion field for each argument to be read. & is the unary address operator, it tells the computer to print the value read at the address reserved for the variable Janice Regan, CMPT 102, Sept. 2006 31 16

Using the fscanf statement: 1 When you declare variables you must also declare a variable of type FILE which will be used to reference the file within your program FILE * DataFileExp1 Before you can read data from a file you must open it using fopen DataFileExp1 = fopen("filename", r"); This connects the variable DataFileExp1, known as a file pointer (it points to or references the file) to the file with name filename Janice Regan, CMPT 102, Sept. 2006 32 Using the fscanf statement: 2 Once the file is opened you can read data fscanf(datafileexp1, format string, arg1, ); This will write arguments arg1, (with the format specified in the format string) to the file pointed to by DataFileExp1 (filename). When DataFileExp1 == NULL you have reached the end of the file. You can test for end of file using Flag = feof( DataFileExp1); If Flag == 1 you are at the end of the file When you are finished writing to the file you must close the file filename fclose(datafileexp1); Janice Regan, CMPT 102, Sept. 2006 33 17