Chapter 3 Input and Output

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two.
Principles of Programming Fundamental of C Programming Language and Basic Input/Output Function 1.
Software Development Method. Assignments Due – Homework 0, Warmup Reading – Chapter 2 –
1 Lecture 2  Input-Process-Output  The Hello-world program  A Feet-to-inches program  Variables, expressions, assignments & initialization  printf()
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
1 Key Concepts:  Data types in C.  What is a variable?  Variable Declaration  Variable Initialization  Printf()  Scanf()  Working with numbers in.
Basic Input/Output and Variables Ethan Cerami New York
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Basic Elements of C++ Chapter 2.
Console and File I/O - Basics Rudra Dutta CSC Spring 2007, Section 001.
CS 161 Introduction to Programming and Problem Solving Chapter 13 Console IO Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
Input/Output  Input/Output operations are performed using input/output functions  Common input/output functions are provided as part of C’s standard.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students C File Input and Output Checking input for errors.
11 Chapter 3 DECISION STRUCTURES CONT’D. 22 FORMATTING FLOATING-POINT VALUES WITH THE DecimalFormat CLASS We can use the DecimalFormat class to control.
CMPE13 Cyrus Bazeghi Chapter 18 I/O in C. CMPE Standard C Library I/O commands are not included as part of the C language. Instead, they are part.
Chapter 5: Data Input and Output Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills
CP104 Introduction to Programming File I/O Lecture 33 __ 1 File Input/Output Text file and binary files File Input/output File input / output functions.
C Tokens Identifiers Keywords Constants Operators Special symbols.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Structure of a C program Preprocessor directive (header file) Program statement } Preprocessor directive Global variable declaration Comments Local variable.
DATA TYPE AND DISPLAY Computer Programming Asst. Prof. Dr. Choopan Rattanapoka and Asst. Prof. Dr. Suphot Chunwiphat.
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
CSCI 3133 Programming with C Instructor: Bindra Shrestha University of Houston – Clear Lake.
9/29/99B-1 CSE / ENGR 142 Programming I Variables, Values, and Types © 1998 UW CSE.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Input and Output.
1 CSC103: Introduction to Computer and Programming Lecture No 28.
Characters and Strings
CS 1704 Introduction to Data Structures and Software Engineering.
A.Abhari CPS1251 Topic 2: C Overview C Language Elements Variable Declaration and Data Types Statement Execution C Program Layout Formatting Output Interactive.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
Files A collection of related data treated as a unit. Two types Text
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand the basic properties and characteristics of external files ❏ To.
Lecture 20: C File Processing. Why Using Files? Storage of data in variables and arrays is temporary Data lost when a program terminates. Files are used.
Connecting to Files In order to read or write to a file, we need to make a connection to it. There are several functions for doing this. fopen() – makes.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
C Language Elements Preprocessor Directives # (sign for preprocessor directive commands) #include Standard header file (.h) Library.
Chapter 18 I/O in C Original slides from Gregory Byrd, North Carolina State University Modified slides by C. Wilcox, Y. Malaiya Colorado State University.
+ Note On the Use of Different Data Types Use the data type that conserves memory and still accomplishes the desired purpose. For example, depending on.
Formatted I/O ä ä Standard Output ä ä printf() family of functions ä ä Standard Input ä ä scanf() family of functions.
Chapter Topics The Basics of a C++ Program Data Types
Lesson #2 Introduction to C.
Lesson #2 Introduction to C.
Chapter 7 Text Input/Output Objectives
Chapter 7 Text Input/Output Objectives
Chapter 7 Text Input/Output Objectives
Basic Elements of C++.
Chapter 2 Overview of C.
ICS103 Programming in C Lecture 3: Introduction to C (2)
Chapter 18 I/O in C.
DATA HANDLING.
Programming in C Input / Output.
Basic Elements of C++ Chapter 2.
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
Programming in C Input / Output.
Lecture 13 Input/Output Files.
INPUT & OUTPUT scanf & printf.
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
Programming in C Input / Output.
Files.
Conversion Check your class notes and given examples at class.
Lesson #2 Introduction to C.
CPS125 Week
Variables in C Topics Naming Variables Declaring Variables
DATA TYPES There are four basic data types associated with variables:
Files Chapter 8.
Presentation transcript:

Chapter 3 Input and Output C Programming for Scientists & Engineers with Applications by Reddy & Ziegler

3.1 Input and Output Functions Formatted Input and Output Functions Standard Input Function Standard Output Function

Standard Input Function For input from the keyboard: scanf(“format control string”, &var1, &var2, ..., &varn); or For input from an input data file: fscanf(stdin, “format control string”, &var1, &var2,…, &varn); Programming Rule: The addresses of the input variables must be specified in the scanf() function.

Reading Data From the Keyboard scanf (“%f %lf”, &income, &expense); Pass these auguments to scanf Convert the first keyboard data to a float type value and store the value in memory cell reserved for the variable income. Conversion specifications Note that %lf is for a double value The addresses of the variables, income and expense Use the “address of” operator, &, to pass the addresses of variables to functions

Using scanf() for input scanf(“ %f %lf ”, &income, &expense ); And then saved in a float type variable income And then saved in a double type variable expense Will be converted to float type using %f Will be converted to double type using %lf Double type variable Address of double type variable First keyboard input Second keyboard input

Operation of scanf function Value expressed as int or float Keyboard input value Value in correct memory cell scanf scanf statement In source code Addresses of memory cell and way to store the value

Standard Output Function For output to the monitor or printer: printf(“format control string”, var1, var2, var3,…, varn); or For output to an output data file fprintf(stdout, “ format control string”, var1, var2, var3,…, varn);

Sample C Program 2.5.1 sample code /*******************************************************/ /* */ /* THIS IS THE FIRST COMPLETE C PROGRAM */ /* */ #include <stdio.h> int main() { int x, y, sum; x = 5; y = 6; sum = x + y; printf("x = %d y = %d sum = %d\n", x, y, sum); return 0; }

For input and output the format control specifications for the built-in data types are: For data type int : %d For data type float : %f For data type double : %lf or %e For data type char : %c For data type character string : %s

3.2 File Input and Output Declaration of File Pointers open and close Statements Input from a Data File Output to a Data File

Declaration of File Pointers A file pointer for input and output files must be declared. The declaration of the file pointers are as follows: FILE *inptr, *outptr; The word FILE must be in uppercase letters; you cannot use lowercase letters. The file pointer name must be preceded by an asterisk(*).

Input and output data files For input: inptr = fopen(“inputfile.dat” , “r”); For output: outptr = fopen(“outputfile.dat” , “w”);

Close data files fclose(inptr); fclose(outptr); There are several options other than “r” and “w” for file operations listed in the text.

Input from an input data file fscanf(inptr , “format control string”, &var1, &var2, &var3, ……..,&varn); Instead of scanf for standard input, use fscanf for input from a data file. The first parameter must be the input file pointer.

Reading Data From A File What function is most commonly used to read data from a file? fscanf(file_pointer, format_string, argument_list); Read the content of the file by file_pointer according to the conversion specifications in format_string The contents read are put into the addresses given by the argument_list. fscanf(inptr, “%d %lf”, &kk, &xx); The functions scanf and fscanf are closely related.

Reading Data From A File What is a file pointer? A file pointer is a variable whose memory cell contains an address, which gives the key to accessing the file stored on disk. FILE *inptr; What is the convention for naming file pointers? The same as naming conventions for C identifiers

Reading Data From A File What is FILE? A type set up for holding information about disk files C derived data type in the header file stdio.h, which must be included to use FILE Use the data type FILE to declare a file_pointer and use this file_pointer to handle your file FILE file_pointer actual file FILE “L3_6.IN”; (Wrong!!)

Reading Data From A File How to open and close the file? Use the C library function fopen( ) to create a link between a disk file and a file pointer. file_pointer = fopen(file_name, access_mode); inptr = fopen(“C3_6.IN”, “r”); “r” means the file is opened for reading in text mode. Use fclose( ) function to close a file manually. fclose(file_pointer); Run source code

Source Code #include <stdio.h> void main(void) { double xx ; int ii, kk; FILE *inptr; inptr = fopen ("C3_6.IN","r"); fscanf(inptr, "%d", &ii); fscanf(inptr, "%d %lf", &kk, &xx); fclose(inptr); printf("ii = %5d\n kk = %5d\n xx = %9.3lf\n",ii, kk, xx); }

Output to an output data file fprintf(outptr , “format control string”, var1, var2, var3, ……..,varn); Instead of printf for standard output, use fprintf for output to a data file. The first parameter must be the output file pointer as shown

Writing Output to A File Topics Writing data to a file Using the fprintf( ) function Previous programs have displayed all their output on the screen. May be convenient Once the screen scrolls or cleans, the output is lost

Writing Output to A File An output file, Can have any acceptable file name Must be linked with a file pointer before it’s used. Must be open before it’s used Should be closed after it’s used

Writing Output to A File What function is used to write data to a file? fprintf(file_pointer, format_string, argument_list) The fprintf( ) function writes the values of argument_list using the given format_string to a file that is linked to the program with the file pointer of file_pointer. fprintf(myfile, “week=%5d\n year=%5d\n”, week, year); The function fprintf is closely related to printf (like fscanf being related to scanf)

Operations of fprintf Function Call to fprintf in source code File pointer Indicating disk file My file Variable Value with formatting Disk file indicated by file pointer %7.2lf fprintf Conversion specification Variable names income

Writing Output to A File What function is used to open an output file and to create a link between the file pointer and file? Before data can be written to an external file, the file must be opened using the fopen( ) function file_pointer = fopen(file_name, access_mode); myfile = fopen(“L3_8.OUT”, “w”); Use the fclose( ) function to close an output file Run source code

Writing Output to A File #include <stdio.h> void main(void) { double income=123.45, expenses=987.65; int week=7, year=1996; FILE *myfile; myfile = fopen("L3_8.OUT","w"); fprintf(myfile,"Week = %5d\n Year = %5d\n",week,year); fprintf(myfile,"Income = %7.2lf\n Expenses = %8.3lf\n", income,expenses); fclose(myfile); }

3.3 Filed Width Specification Input Field Width Specification Output Field Width Specification

Field Width Specification In the format control string, the field width for each of the control fields can be specified for both input and output. The specification of field width to align the output data properly is very important, because the alignment increases the readability of output displayed on the monitor, printed, or written to a data file.

%nd for integers %nd for integers, where n must be a numeric literal which specifies the format field width for locating integers to input. Examples are as follows: %7d %10d %12d These specifications provide 7 spaces, 10 spaces, and 12 spaces, respectively, for three integer numbers.

%nf for real numbers %nf for real numbers, n must be a numeric literal which specifies the number of total decimal digits to be input possibly including a leading sign and a decimal point. %8f %10f These specifications mean the decimal numbers with sign and decimal point are found within the next 8 and 10 positions

example With the field width specification %8.2f, the spaces are allocated as follows: 2 spaces for the fractional digits 1 space for the decimal point 1 space for the sign 4 spaces for the whole digits

3.4 Input and Output of Characters Standard Input and Output File Input and Output Unformatted Input and Output

Input and Output of Characters Characters are stored internally in a code such as ASCII. The ASCII code for characters is presented in Appendix A. Each character is allocated one byte of storage. One byte of memory can hold decimal numbers in the range of 0 to 255. Therefore one byte of storage is enough to store 256 different character codes. Character variables are declared using the basic data type char

Standard input of characters scanf(“%c%c%c”, &chr1, &chr2, &chr3); assume data is xyz There are no blank spaces in XYZ because there are no blank spaces in the format control string in the input statement. Notice that %c is the format control string for character data.

standard output of characters printf(“%c %c %c”, chr1, chr2, chr3); The output is as follows: X Y Z If the format string is %d instead %c: printf(“%d %d %d”, chr1, chr2, chr3); The output is as follows: 88 89 90

Input from a data file FILE *inptr; char chr1, chr2, chr3, chr4; inptr = fopen(“infile.dat”, “r”); fscanf(inptr, “%c%c%c%c”, &chr1, &chr2, &chr3, &chr4); The input data is as follows: 3 XY stored in memory as:

Output of character data to an output data file FILE *outptr; outptr = fopen(“outoutfile.dat”, “w”): char chr1 = ‘3’, chr2 = ‘ ‘, chr3 = ‘X’, chr4 = ‘Y’; fprintf(outptr, “%c%c%c%c”, chr1, chr2, chr3, chr4); The output is as follows: 3 XY

3.5 Sample Programs Conversion from Polar to Cartesian Coordinates Cost of a Steel Cage Convection Heat Transfer Air Conditioners Sales Report Wavelength of Electron