Iosif Ignat & Marius Joldoș Laboratory Guide 1. Standard I/O. Standard I/O in C

Similar documents
ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

So far we have considered only numeric processing, i.e. processing of numeric data represented

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

2 ASCII TABLE (DOS) 3 ASCII TABLE (Window)

Informatica e Sistemi in Tempo Reale

The programming language C. sws1 1

Sources: On the Web: Slides will be available on:

System Calls and Standard I/O

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

File Handling. What is a file?

How To Write Portable Programs In C

C PROGRAMMING FOR MATHEMATICAL COMPUTING

As previously noted, a byte can contain a numeric value in the range Computers don't understand Latin, Cyrillic, Hindi, Arabic character sets!

Computer Science 2nd Year Solved Exercise. Programs 3/4/2013. Aumir Shabbir Pakistan School & College Muscat. Important. Chapter # 3.

The C Programming Language course syllabus associate level

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

Base Conversion written by Cathy Saxton

Chapter 4: Computer Codes

Chapter One Introduction to Programming

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Oct: 50 8 = 6 (r = 2) 6 8 = 0 (r = 6) Writing the remainders in reverse order we get: (50) 10 = (62) 8

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

System Calls Related to File Manipulation

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Install Java Development Kit (JDK) 1.8

C++ Language Tutorial

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

This is great when speed is important and relatively few words are necessary, but Max would be a terrible language for writing a text editor.

Tutorial on C Language Programming

LOW LEVEL FILE PROCESSING

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Pemrograman Dasar. Basic Elements Of Java

Exceptions in MIPS. know the exception mechanism in MIPS be able to write a simple exception handler for a MIPS machine

Illustration 1: Diagram of program function and data flow

Module 816. File Management in C. M. Campbell 1993 Deakin University

Reading Delimited Text Files into SAS 9 TS-673

Secrets of printf. 1 Background. 2 Simple Printing. Professor Don Colton. Brigham Young University Hawaii. 2.1 Naturally Special Characters

C++ Input/Output: Streams

Channel Access Client Programming. Andrew Johnson Computer Scientist, AES-SSG

Member Functions of the istream Class

3 IDE (Integrated Development Environment)

Operating Systems. Privileged Instructions

Basics of I/O Streams and File I/O

sqlite driver manual

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

1 Abstract Data Types Information Hiding

Technical Paper. Reading Delimited Text Files into SAS 9

Chapter 2: Elements of Java

Variables, Constants, and Data Types

C / C++ and Unix Programming. Materials adapted from Dan Hood and Dianna Xu

Lecture 5: Java Fundamentals III

Simple C Programs. Goals for this Lecture. Help you learn about:

Storing Measurement Data

arrays C Programming Language - Arrays

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

Lecture 22: C Programming 4 Embedded Systems

This section describes how LabVIEW stores data in memory for controls, indicators, wires, and other objects.

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

/* File: blkcopy.c. size_t n

2010/9/19. Binary number system. Binary numbers. Outline. Binary to decimal

Passing 1D arrays to functions.

1. Give the 16 bit signed (twos complement) representation of the following decimal numbers, and convert to hexadecimal:

Number Representation

B.Sc.(Computer Science) and. B.Sc.(IT) Effective From July 2011

2011, The McGraw-Hill Companies, Inc. Chapter 3

Chapter 7 Assembly Language

Useful Number Systems

C++ INTERVIEW QUESTIONS

C Examples! Jennifer Rexford!

Fundamentals of Programming

5 Arrays and Pointers

ASSEMBLY PROGRAMMING ON A VIRTUAL COMPUTER

Arithmetic in MIPS. Objectives. Instruction. Integer arithmetic. After completing this lab you will:

Answers to Review Questions Chapter 7

Computers. Hardware. The Central Processing Unit (CPU) CMPT 125: Lecture 1: Understanding the Computer

Introduction to Python

Lecture 24 Systems Programming in C

The Windows Shortcut File Format as reverse-engineered by Jesse Hager Document Version 1.0

Compilers Lexical Analysis

13 Classes & Objects with Constructors/Destructors

C Interview Questions

Stacks. Linear data structures

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

6.1. Example: A Tip Calculator 6-1

Caml Virtual Machine File & data formats Document version: 1.4

The New IoT Standard: Any App for Any Device Using Any Data Format. Mike Weiner Product Manager, Omega DevCloud KORE Telematics

Data Storage. Chapter 3. Objectives. 3-1 Data Types. Data Inside the Computer. After studying this chapter, students should be able to:

Simple Image File Formats

10CS35: Data Structures Using C

Character Translation Methods

Formatting Numbers with C++ Output Streams

Crash Dive into Python

ASSEMBLY LANGUAGE PROGRAMMING (6800) (R. Horvath, Introduction to Microprocessors, Chapter 6)

Building Java Programs

Outline. hardware components programming environments. installing Python executing Python code. decimal and binary notations running Sage

The Answer to the 14 Most Frequently Asked Modbus Questions

Transcription:

Standard I/O in C 1. Overview The learning objective of this lab is: To understand the structure of simple, one function programs in C To use simple input and output statements (reading/writing from/to the standard I/O files). 2. Brief theory reminder The standard device is the one used to start a program. There are two files attached to this device: the standard input file (named stdin) and the standard output file (named stdout). These files are sequential files. The frequently used C/C++ library functions for I/O operations are: For input: getch, getche, gets, scanf, sscanf ; For output: putch, puts, printf, sprintf. Macros getchar, for input, and putchar, for output, supplement these set. 2.1. getch, getche and putch functions (MS-DOS/Windows specific) getch reads without echoing a character when a character is input from the keyboard. The key may have an ASCII code or a special function attached. In the first case, the function returns the ASCII code for that character. In the second case the function must be invoked twice: at the first call, it returns the value zero, and at the second call it returns a specific value for the pressed key. getche has similar functionality. The difference is that the read character is echoed. When getch or getche are invoked, the system waits for a key to be pressed. putch sends to the output device (e.g. screen) a character which corresponds to the ASCII code used as its argument. Printable characters have ASCII codes in the range [32,126]. Codes outside this range cause various image patterns to be displayed. This function returns its argument. The prototypes for these functions are in the header file conio.h 1. They are as follows: int getch(void); int getche(void); int putch(int ch); 1 conio.h is a header file used in old MS-DOS compilers, to create text mode user interfaces, however, it is not part of the C programming language, the C standard library, ISO C or by POSIX. This header declares several useful library functions for performing "console input and output" from a program. Most C compilers that target DOS, Windows 3.x, Phar Lap, DOSX, OS/2, or Win32 have this header and supply the concomitant library functions in the default C library. Most C compilers that target UNIX and Linux do not have this header and do not supply the concomitant library functions. The library functions declared by conio.h vary significantly from compiler to compiler. As originally implemented in Microsoft's Visual C++ the various functions mapped directly to the first few DOS int 21h functions. But the library supplied with Turbo C++ and Borland C++ did not use the DOS API but instead accessed video RAM directly for output and used BIOS interrupt calls. Compilers that targeted non-dos operating systems, such as Linux, Win32 and OS/2, provided different implementations of these functions. T.U. Cluj-Napoca Computer Programming 1

A usage example is: /* Program L1Ex1.c */ #include <conio.h> int main() putch(getch()); getch(); 2.2. gets and puts functions gets reads with echo from the standard input device an ASCII string, and places this string in the variable given as its argument. Upon return reading continues with: Character '\n' (newline), which is replaced by character '\0' (null). In this case, gets return the start address for the memory area where read characters are stored. End of file marker (CTRL/Z). gets returns the value zero. puts displays on the standard output device a character string corresponding to the ASCII codes of the characters stored at the address given as its argument. The null character ('\0') is interpreted as newline ('\n'). This function returns the code of the last displayed character or the value 1 in case that an error occurred. Prototypes for these functions can be founding the header file stdio.h. They are: char *gets (char *s); int puts (const char *s); Here *s denotes a pointer to an ASCII string (e.g. a string variable). A usage example is: /* Program L1Ex2.c */ int main() char s[200]; printf("\nplease input a character string and press ENTER\n"); gets(s); printf("\nthe character string is\n"); puts(s); 2.3. scanf and printf T.U. Cluj-Napoca Computer Programming 2

scanf is intended for inputting data which are interpreted as specified by formatting information. Input data are converted from their external representations to the corresponding internal representations and are stored in the variables provided as arguments. End of input is signaled when the ENTER key is pressed. The prototype for scanf is located in the header file named stdio.h, and is as follows: int scanf(const char *format, variable list ); scanf returns the number of input fields successfully converted or the value 1 (EOF) if the end of file (EOF for short) is encountered during conversion. EOF can be signaled by pressing CTRL/Z in Windows/MS-DOS operating systems. The format for scanf is specified as a character string enclosed in double quotation marks ("). The format string includes format specifiers, which define the conversion rules from output to input representations. A format specifier is composed of: The character '%'. The optional character '*', which indicates that the result of the input data conversion will not be assigned to any variable. An optional decimal number, which defines the maximum length of the field controlled by the format specifier. One or two letters, which define the type of conversion. The field controlled by the format begins with the first non-whitespace character (whitespace means blanks or tabs), and is terminated, as the case stands: At the character following a whitespace. At the character which does not satisfy the type of conversion. At the character where the maximum legth of the field is reached. When using the standard input, the data is read after the user presses the ENTER key. The address of a variable is specified as &variable_name for scalars and as array_variable name (note that there is no & in front) for single dimensional arrays (e.g. for character strings). The letters defining the type of conversion are given in the table below. Letter Type of read data c Character (char) s Character string (char *) d Decimal integer o Octal integer x, X Hexadecimal integer u Unsigned integer f Floating point (real) number ld, lo, lx, lx Long lu Unsigned long lf/lf Double/long double printf is used for printing formatted data, e.g. on the screen. Data are converted from the internal representation into an external representation using the specified format descriptors. The prototype for printf is located in the header file stdio.h, and is as follows: int printf(const char *format,expression list ); T.U. Cluj-Napoca Computer Programming 3

The format is, as with scanf, given as a character string. It containg character sequences which are to be printed and format descriptors. A format descriptor (aka format specifier) contains: The character '%'. An optional minus ('-') character, which specifies that the data to be printed will be left-justified (the default justification is right-justification). An optional decimal number, which defines the minimum length (character count) of the field which will hold the printed data. And optional dot ('.') followed by a decimal number specifying the precision. One or two letters, which define the type of conversion. In addition to the letters used with scanf, letters 'e' or 'E' can also be used for printing floating point data (in single or double precision) in scientific notation, letters 'g' or 'G' specifying that the floating point data is to be printed in either the usual way or in scientific notation such as it yields a field of a minimum length. printf returns the number of successfully printed characters on success, and -1 in case an error occurs. Usage examples: /* Program L1Ex3.c */ int main( ) int a; float b, c; printf("\nplease input the integer value of a="); scanf("%5d",&a); printf("\nplease input the value of the real number b="); scanf("%5f",&b); c=a+b; printf("\nthe value of the sum c=a+b is: %6.3f\n",c); 2.4. sscanf and sprintf As a difference from the functions scanf and printf, sscanf and sprintf have a supplemental first argument indicating the memory area holding ASCII strings. sscanf uses that area to read characters instead the standard input. For sprintf the memory area indicated by its first argument is used for output, instead of the standard output device (e.g instead of the screen). Prototypes for these functions are supplied in stdio.h: int sscanf (const char *buffer, const char *format,variable list ); int sprintf (char *buffer, const char *format,expression list ); Usage sample: /* Program L1Ex4.c */ int main() T.U. Cluj-Napoca Computer Programming 4

char s[100], q[100]; int a, b; float c, d; printf ("\ninput on the same row values for integer a and real c\n\ separated by a whitespecs character\n\ and followed by ENTER\n"); gets(s); sscanf(s,"%d %f", &a, &c); printf("\n a=%4d c=%8.3f\n", a, c); sprintf(q,"%4d %8.3f\n", a, c); sscanf(q,"%d %f",&b,&d); printf("\n b=%5d d=%9.4f\n",b,d); 2.5. getchar and putchar The getchar macro enables reading with echo of ASCII characters (no special keys allowed). The characters keyed in are placed in a buffer and not converted till the ENTER key is pressed. Upon return, the ASCII code of the first input character is returned. When invoked again the next input character is returned, a.s.o. When EOF is encountered, getchar returns the value 1. The putchar macro prints the character given as an argument. Macros getchar and putchar are defined in stdio.h as follows: int getchar(void); int putchar (int c); and are invoked in the same way as getch and putch. Usage example: /* Program L1Ex5.c */ int main( ) putchar(getchar()); putchar('\n'); 3. Lab Tasks 3.1. Run the programs given as examples and analyze the output. 3.2. Write a program to check how getch is executed when a special key (F1 to F12, CTRL/another key) is pressed. 3.3. Write a program to check what putch outputs when its argument is a value outside the range [32,126]. 3.4. Write a program to print the ASCII codes for the keys of your keyboard. T.U. Cluj-Napoca Computer Programming 5

3.5. Write a program to print the characters corresponding to the ASCII codes in the range [32,126]. 3.6. Write a program to containing invocation(s) of gets(s), where s is an array. Check the contents of each array member. Why the newline character ('\n') was replaced by '\0'? 3.7. Write a program to read a lowercase letter string and print the corresponding uppercase letter string. 3.8. Write a program to read a uppercase letter string and print the corresponding lowercase letter string. 3.9. Write a program to calculate the sum, difference, product and quotient of a pair of real numbers. Output the results as a table: x y x+y x-y x*y x/y 3.10. Write a program to print the number π = 3.14159265 using various format descriptors. 3.11. Write a program to print an integer read from the keyboard in its octal and hexadecimal representations. T.U. Cluj-Napoca Computer Programming 6