Lecture 4. Console input/output operations. 1. I/O functions for characters 2. I/O functions for strings 3. I/O operations with data formatting

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

Fundamentals of Programming

Unit 4. Input/Output Functions

Fundamental of Programming (C)

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

Outline. Computer Programming. Preprocessing in C. File inclusion. Preprocessing in C

Computer Programming Unit v

C Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;

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

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

Standard File Pointers

sends the formatted data to the standard output stream (stdout) int printf ( format_string, argument_1, argument_2,... ) ;

Introduction to Computing Lecture 03: Basic input / output operations

Console Input and Output

Chapter 8: Character & String. In this chapter, you ll learn about;

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

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

UNIT-V CONSOLE I/O. This section examines in detail the console I/O functions.

Input / Output Functions

Standard I/O in C and C++

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

The C Programming Language Part 2. (with material from Dr. Bin Ren, William & Mary Computer Science)

UNIT-I Input/ Output functions and other library functions

Strings. Daily Puzzle

Library Functions. General Questions

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

Advanced C Programming Topics

Chapter 5, Standard I/O. Not UNIX... C standard (library) Why? UNIX programmed in C stdio is very UNIX based

Formatted Output Pearson Education, Inc. All rights reserved.

Data Input and Output 187

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

Characters in C consist of any printable or nonprintable character in the computer s character set including lowercase letters, uppercase letters,

1/31/2018. Overview. The C Programming Language Part 2. Basic I/O. Basic I/O. Basic I/O. Conversion Characters. Input/Output Structures and Arrays

Computers Programming Course 5. Iulian Năstac

Introduction to Programming

BSM540 Basics of C Language

This code has a bug that allows a hacker to take control of its execution and run evilfunc().

Simple Output and Input. see chapter 7

Fundamentals of Programming Session 8

11 Console Input/Output

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7

BİL200 TUTORIAL-EXERCISES Objective:

Department of Computer Applications

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

Pointers cause EVERYBODY problems at some time or another. char x[10] or char y[8][10] or char z[9][9][9] etc.

Binghamton University. CS-220 Spring Includes & Streams

Standard C Library Functions

Fundamentals of Programming. Lecture 11: C Characters and Strings

7/21/ FILE INPUT / OUTPUT. Dong-Chul Kim BioMeCIS UTA

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types

Programming and Data Structures

Fundamental of Programming (C)

BSM540 Basics of C Language

Fundamentals of Programming. Lecture 10 Hamed Rasifard

Text Output and Input; Redirection

8. Characters, Strings and Files

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

C Programming. Unit 9. Manipulating Strings File Processing.

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

Formatting functions in C Language

ONE DIMENSIONAL ARRAYS

THE FUNDAMENTAL DATA TYPES

Lecture 3. More About C

Intermediate Programming, Spring 2017*

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

Fundamentals of Programming

As stated earlier, the declaration

Chapter 7. Basic Types

upper and lower case English letters: A-Z and a-z digits: 0-9 common punctuation symbols special non-printing characters: e.g newline and space.

'C' Programming Language

Data Types and Variables in C language

Input/Output and the Operating Systems

Should you know scanf and printf?

AWK - PRETTY PRINTING

MODULE 3: Arrays, Functions and Strings

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

File IO and command line input CSE 2451

System Software Experiment 1 Lecture 7

CSE 12 Spring 2016 Week One, Lecture Two

Programming & Data Structure: CS Section - 1/A DO NOT POWER ON THE MACHINE

Course organization. Course introduction ( Week 1)

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

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

scanf erroneous input Computer Programming: Skills & Concepts (CP) Characters Last lecture scanf error-checking our input This lecture

WARM UP LESSONS BARE BASICS

CC112 Structured Programming

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

CpSc 1111 Lab 4 Formatting and Flow Control

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011

UNIT 3 OPERATORS. [Marks- 12]

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

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

C FILE Type. Basic I/O in C. Accessing a stream requires a pointer variable of type FILE.

C Basics And Concepts Input And Output

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

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

Reserved Words and Identifiers

ECET 264 C Programming Language with Applications. C Program Control

Chapter 8 - Characters and Strings

Quick review of previous lecture Ch6 Structure Ch7 I/O. EECS2031 Software Tools. C - Structures, Unions, Enums & Typedef (K&R Ch.

Transcription:

Lecture 4 Console input/output operations 1. I/O functions for characters 2. I/O functions for strings 3. I/O operations with data formatting

Header files: stdio.h conio.h C input/output revolves around the notion of a data stream, where we can insert data into an output stream or extract data from an input stream. There are 5 predefined logical devices which are automatically created at the execution of the program and are automatically closed at the end of execution: stdin stream of type text standard input - keyboard. stdout stream of type text standard output - monitorul; stderr - stream of type text standard output for errors monitorul strprn binary stream standard output - printer (DOS PRN). stdaux binary stream standard input/output - DOS AUX.

I/O functions for characters Input functions: int getchar(void); int getche(void); int getch(void); // defined in stdio.h // defined in conio.h // defined in conio.h Output functions: int putchar(int c); int putch(int c); // defined in stdio.h // defined in conio.h

char ch; ch=getchar(); ch=getche(); ch=getch(); getch(); // variable ch is declared; it can get value by one of // the functions that read a character // function getchar() returns the value of typed // character (corresponding value in ASCII); it is taken // by variable ch, but only after pressing Enter; the // character is displayed // function getchar() returns the value of typed // character (corresponding value in ASCII); it is taken // by variable ch, without waiting pressing Enter; the // character is displayed // function getchar() returns the value of typed // character (corresponding value in ASCII); it is taken // by variable ch, without waiting pressing Enter; // the character is not displayed // function getch () returns the value of typed // character without this amount is used; this // instruction is typically used to pause program // execution by pressing a key, the character is not // displayed on the screen

char ch = a ; putch( x ); putchar( y ); putch(ch); putch( \n ); putchar( \r ); putchar(99); putchar(0x63); // declaration of variable ch character // is displayed a constant character // is displayed a constant character // is displayed the contents of the variable ch (the // character a ) // constant character \n (newline) is not displayed, // but moves the cursor to next line // constant character \r (CR-carriage return) is not // displayed, but moves the cursor to beginning of // row // is displayed the constant character with // corresponding value in ASCII 99, character c // is displayed the constant character with // corresponding value in ASCII 0x63, character c

I/O operation for strings Input function: char * gets(char * s); // defined in stdio.h Output operation: int puts (const char * s); // defined in stdio.h Note: In C / C + + strings are not defined by a predefined data type, but are built as arrays with elements of type char. Strings are composed of sequences of characters entered with the character (double quota) end finished by \0 ; (zero in ASCII code). A string is declared like: char string_name [ characer_no ] ;

char str1[30]= first string"; // declaration of string with initialization char str2[30]= second string"; // declaration of string with initialization puts("str1:"); puts(str1); puts("str2:"); puts(str2); puts("\ninput a string:"); gets(str1); puts("\ninput a string:"); gets(str2); puts("str1:"); puts(str1); puts("str2:"); puts(str2); // displays the constant string str1: // displa s the content of string str1 // displa s the constant string str2: // displa s the content of string str1 // reads the contents of the string str1 from // keyboard // reads the contents of the string str1 from // keyboard // displays the content of the string str1, that is the // contents entered from the keyboard // displays the content of the string str2, that is the // contents entered from the keyboard

I/O Operations with format They work with all fundamental types of data. Input operations int scanf(const char* format_string, [list_of_addresses]); Output operations int printf(const char* format_string, [list_of_values]);

Format specifyers Code Signification (type of data) %c Character %d Decimal integer %i Decimal integer %u Unsigned decimal integer %o Octal integer %x Hexadecimal integer %X Hexadecimal integer %f Real floating point %e Real floating point scientific format %E Real floating point scientific format %g Real floating point %G Real floating point %s String %p Memory address in hexadecimal %[ ] Find a set of characters

scanf() - function call syntax

printf() - function call syntax

Modelators of format field magnitude precision + forces printing of + sign - forces the display to align left; # - prints 0 as prefix for octal representation and 0x for hexadecimal Specifier for field magnitude Specifier for precision printf ( %+5d %12.2f, 123, -123.4567 ); Modelator for displaying sign

printf ( \n*%f*, 12.3456); // it displays by default 6 decimals printf ( \n*%10.2f*,12.3456); // it specifies the number of characters of // the field (10 - number of characters // shown) and precision (two decimals) printf ( \n*%+10.2f*, 12.3456); // it displays the sign + printf ( \n*%+010.2f*, 12.3456); // unused characters of the field will be // filled with 0 Result of program execution: *12.345600* * 12.34* * +12.34* *0000+12.34*

It is possible that a I/O function to find the residual data remaining in the buffer from previous operations for different reasons, such as exceeding the size of fields, use of illegal characters, etc. To avoid taking the residual data is necessary before the I/O operation to empty out the buffer. This operation can be done using the function fflush(), defined in stdio.h file that has the prototype: int fflush(file* stream); int a, b; scanf( %2d, &a); scanf( %2d, &b); fflush(stdin); scanf( %2d, &a); fflush(stdin); scanf( %2d, &b);

- examples #include <stdio.h> main() { int i = 0; i=printf("abcde\n"); printf("total characters printed %d\n",i); } The result

- examples Use multiple conversion specifiers in a single printf statement #include <stdio.h> main() { char firstinitial, middleinitial, lastinitial; firstinitial= 'M'; middleinitial= 'A'; lastinitial= 'V'; printf("my Initials are %c.%c.%c.", firstinitial, middleinitial, lastinitial); } The result

- examples Use multiple conversion specifiers in a single printf statement #include <stdio.h> int main() { int i = 873; double f = 123.94536; char s[] = "Happy Birthday"; printf( "Using dimension of field for integers\n" ); printf( "\t%04d\n\t%09d\n\n", i, i ); printf( "Using precision for floating-point numbers\n ); printf( "\t%.3f\n\t%.3e\n\t%.3g\n\n", f, f, f ); printf( "Using dimension of field for strings\n" ); printf( "\t%11s\n", s ); return 0; } The result:

- examples Use multiple conversion specifiers in a single printf statement #include <stdio.h> int main(void) { float fp1 = 0.0f; float fp2 = 0.0f; float fp3 = 0.0f; int value_count = 0; printf("input:\n"); value_count = scanf("%e %g %f", &fp1, &fp2, &fp3); printf("return value = %d", value_count); printf("\nfp1 = %f fp2 = %f fp3 = %f\n", fp1, fp2, fp3); return 0; } The result

- examples Read strings from keyboard #include <stdio.h> #include <string.h> int main(void) { char word1[20]; printf("\ntype in the first word:\n "); scanf("%19s", word1); printf("\n%19s",word1); printf("\n%-19s",word1); return 0; } The result

- examples Inputting data with a field width #include <stdio.h> int main() { int x; int y; printf( "Enter a six digit integer: " ); scanf( "%2d%d", &x, &y ); printf( "The integers input were %d and %d\n", x, y ); return 0; } The result

- examples Using a scan set #include <stdio.h> int main() { char z[ 9 ]; printf( "Enter string: " ); scanf( "%[aeiou]", z ); printf( "The input was \"%s\"\n", z ); return 0; } The result

- examples Inputting integers Note the '&' sign before c. &c denotes the address of c and value is stored in that address. #include <stdio.h> int main() { int c; printf("enter a number\n"); scanf("%d", &c); printf("number=%d", c); return 0; } The result Enter a number 4 Number=4

- examples I/O of characters and ASCII code #include <stdio.h> int main() { char var1; printf("enter character: "); scanf("%c",&var1); printf("you entered %c.",var1); return 0; } The result Enter character: g You entered g.

- examples I/O of characters and ASCII code When character is typed in the above program a numeric value (ASCII value) is stored. And when we displayed that value by using "%c", that character is displayed. #include <stdio.h> int main() { char var1; printf("enter character: "); scanf("%c",&var1); printf("you entered %c.\n",var1); printf("ascii value is %d",var1); return 0; } The result Enter character: g You entered: g ASCII value is 103

- examples Variations in Output for integer an floats Integer and floating-points can be displayed in different formats in C programming #include <stdio.h> int main() { /* Prints the number right justified within 6 columns */ printf("case 1:%6d\n",9876); /* Prints the number to be right justified to 3 columns but, there are 4 digits so number is not right justified */ printf("case 2:%3d\n",9876); /* Prints the number rounded to two decimal places */ printf("case 3:%.2f\n",987.6543); /* Prints the number rounded to 0 decimal place, i.e, rounded to integer */ printf("case 4:%.f\n",987.6543); } /* Prints the number in exponential notation(scientific notation) */ printf("case 5:%e\n",987.6543); return 0; The result: Case 1: 9876 Case 2:9876 Case 3:987.65 Case 4:988 Case 5:9.876543e+002