Standard I/O in C and C++

Size: px
Start display at page:

Download "Standard I/O in C and C++"

Transcription

1 Introduction to Computer and Program Design Lesson 7 Standard I/O in C and C++ James C.C. Cheng Department of Computer Science National Chiao Tung University

2 Standard I/O in C There three I/O memory buffers in the computer FILE* stdin For the standard input device (generally, a keyboard). FILE* stdout For the standard output device (generally, the screen). FILE* stderr For output error and warning messages to the standard output device FILE* is a pointer to point a stream I/O buffer FILE* stdin address data 0x 26E81E00 26E81E00 04 A E81E04 0B F 26E81E08 06 FF E81E0C B4 00 C7 FF 2

3 Standard I/O in C putchar() put a character to stdout Usage: #include <stdio.h> int putchar( int c ); Print c by ASCII returns the printed character Ex: ASCII: American Standard Code for Information Interchange putchar('a'); putchar('b'); putchar('c'); putchar('\n'); /* ABC */ 3

4 Standard I/O in C printf() Put a formatted string of characters to the stdout. Usage: #include <stdio.h> int printf( const char *format [, argument]... ); returns the number of characters printed The results are undefined if there are not enough arguments for all the format specifications. Example: int x = 65; float r = 1.2f; printf("%d\t%d\t%d\n", x, x+1, x+2); /* */ printf("%x\\%x\\%x\n", x, x+1, x+2); /* 41\42\43 */ printf( \"%c%c%c\" \n", x, x+1, x+2); /* "ABC" */ printf( %f, %f, %f \n", r, r+0.1f, r+0.2f); /* , , */ Escape characters (Special function characters): \n newline \t tab \r return \' single quotation \ double quotation \\ backslash \ooo ASCII in octal \xhhh ASCII in hex 4

5 Standard Output in C printf() Basic Format Specification: float r = ; printf("%f, %E, %G\n", r, r, r); printf("%f, %e, %g\n", r, r, r); Output: , E-006, 1.23E , e-006, 1.23e-006 Notice that E(or e) means power of 10, not power of

6 Standard Output in C printf() %+width+.precision + {f/e/e/g/g}, width: the minimum number of characters printed, if width is not given, all characters of the value are printed. precision: for f/e/e : the number of digits after the decimal point, for g/g: the maximum number of significant digits printed. default is six float r = ; printf("%10.8f, %4.2e, %4.2g\n", r, r, r); Output: , 1.23e-006, 1.2e-006 6

7 Standard Output in C printf() Data alignment The memory pre-allocation for each argument: 4-byte arguments: bool, char, int, short, long 8-byte arguments: int x = 10; float r = 0.123f; char c = 65; float, double float r = 0.123f; printf("%f, r); /* 1. Allocate 8 byte to store the vlaue of r float -> double 2. %f will convert the double float to string */ printf("%d, %f, %d, %d\n", x, c, c, x+1, x+2); // Why dose c need to be printed twice? printf("%f, %d%d, %f, %f\n", r, r, r + 1, r + 2); // Why does it print the second r by %d%d? 7

8 Standard Output in C printf() Type cast all float arguments are promoted to double bool, (unsigned)char, (unsigned)short, and (unsigned)int are promoted to (unsigned)long ex unsigned char a = -1; printf("%08x\n", a); int b = -1; printf("%08x\n", b); float f = 0.1f; printf("%x\n", f); printf("%x%x\n", f); // FF // FFFFFFFF // A // A FB = in IEEE bit format 0, , = 3DCCCCCD 16 Then, promotion to 64 bit 0, , = 3FB99999A

9 Standard Input in C scanf() Read formatted data from the standard input stream, the stdin. Usage: #include <stdio.h> int scanf( const char *format [,argument]... ); the format represents that the input format of the stdin White-space characters, WC: blank (' '); tab ('\t'); or newline ('\n'). scanf will read and ignore any WCs which are encountered before the next non-wc from stdin. The non-wcs in format, except the % scanf will read the next character from stdin and compart it to the non-wc. If they are matched, the input character is discarded and the scanf continues. If they are different, the scanf fails, returning and leaving subsequent characters of stdin unread If there is no any non-wc after the last % in the format, then all of the input WCs after the last % will be left in stdin 9

10 Standard Input in C The return of scanf() 1. The number of fields successfully converted and assigned. ex: int a =1, b =2, c =3; printf("%d\n", scanf("%d %d %d", &a, &b, &c) ); printf("%d, %d, %d", a, b, c); If you input 5 6 7, you will see 3 5, 6, 7 If you input 5 6 x, you will see 2 5, 6, 3 If you input 5 x 7, you will see 1 5, 2, 3 10

11 Standard Input in C The return of scanf() 2. EOF End of File usually EOF is defined by (-1) In Windows, using Ctrl+z to input an EOF character. In UNIX, using Ctrl+d to input an EOF character. In Windows, scanf() returns EOF if the first input is Ctrl+z. In Unix, scanf() returns EOF if the first input is Ctrl+d. ex: int n = 0; printf("n = (Ctrl+Z to exit)"); while( scanf("%d", &n)!= EOF ){ if (n & 1) printf("%d is odd\n", n) else printf("%d is even\n", n); printf("n = (Ctrl+Z to exit)"); } 11

12 Standard Input in C scanf() Datatype Specification: Example : float r = 0.0f; double s = 0.0; scanf("%d", &r); printf("f = %f\n", r); scanf("%f", &r); printf("f = %f\n", r); scanf("%f", &s); printf("f = %lf\n", s); scanf("%lf", &s); printf("f = %lf\n", s); 12

13 Standard Input in C scanf() Confusion with White Space : int a=0, R=0; R = scanf("%d", &a); getchar(); // Never stop here! int a=0, b =0, c=0, R=0; R = scanf("%d", &a); printf("a=%d, b=%d, c=%d and R=%d\n", a, b, c, R); R = scanf(" %d", &b); printf("a=%d, b=%d, c=%d and R=%d\n", a, b, c, R); R = scanf("%d ", &c); //?? printf("a=%d, b=%d, c=%d and R=%d\n", a, b, c, R); int a=0, b =0, c=0, R=0; // No difference between these two scanf R = scanf("%d%d%d", &a, &b, &c); printf("a=%d, b=%d, c=%d and R=%d\n", a, b, c, R); R = scanf(" %d \t %d \n %d", &a, &b, &c); printf("a=%d, b=%d, c=%d and R=%d\n", a, b, c, R); 13

14 Standard Input in C scanf() Are these two format specifiers different? int a=0, b =0, c=0, R=0; R = scanf("%d:%d:%d", &a, &b, &c); // bad format! // Try to type 1 :2 :3 printf("a=%d, b=%d, c=%d and R=%d\n", a, b, c, R); int a=0, b =0, c=0, R=0; R = scanf("%d\t:%d\t:%d", &a, &b, &c); // Good format // Try to type 1 : 2 : 3 printf("a=%d, b=%d, c=%d and R=%d\n", a, b, c, R); int a=0, b =0, c=0, R=0; R = scanf("%d\t:\t%d\t:\t%d", &a, &b, &c); // redundant format! // Try to type 1 : 2 : 3 printf("a=%d, b=%d, c=%d and R=%d\n", a, b, c, R); 14

15 Standard Input in C scanf() %*: Read but not store int a=0, b =0, c=0, R=0; R = scanf("%d%d%*d", &a, &b, &c); printf("a=%d, b=%d, c=%d and R=%d\n", a, b, c, R); // In legal input string, c will always be zero! * int a=0, b =0, c=0, R=0; R = scanf("%d%*d%d", &a, &b, &c); printf("a=%d, b=%d, c=%d and R=%d\n", a, b, c, R); // In legal input string, c will always be zero! int a=0, b =0, c=0, R=0; R = scanf("%*d%d%d", &a, &b, &c); printf("a=%d, b=%d, c=%d and R=%d\n", a, b, c, R); // In legal input string, c will always be zero! 15

16 Standard Input in C Using scanf() to read a text string char A[20] = {0}; // Declare a string of 20 zero characters scanf("%s", A); // What if we type ABC EFG XYZ printf("%s\n", A); char A[20] = {0}, B[20] = {0}, C[20] = {0}; scanf("%s %s %s", A, B, C); // Try it again printf("%s %s %s\n", A, B, C); %[ ]: Read the specified characters Input ends when a non-matching character is reached or the field width is reached. char A[20] = {0}, B[20] = {0}, C[20] = {0}; scanf("%[0-9]%[a-z]%[a-z]", A, B, C); printf("%s %s %s\n", A, B, C); scanf("%[ -~, '\t']", A); // Read the characters which ASII are 9 and 32 to 126 printf("%s\n", A); scanf( %[ -~, \t, \n ], A); // Oops. 16

17 Standard Input in C Using scanf() to read a text string %[^ ]: Read the characters except the specified characters char A[20] = {0}, B[20] = {0}, C[20] = {0}; scanf("%[^0-9]%[^a-z]%[^a-z]", A, B, C); printf("%s %s %s\n", A, B, C); scanf("%[^'\n']", A); // Read all characters except \n printf("%s\n", A); 17

18 Standard Input in C stdin should be cleared before using "%[]" to input a string because: int x; char str[10] = {0}; scanf("%d",&x); // After you type "123" + ENTER, then "123"x and stdin = "\n" cout << x << endl; scanf("%[0-9]",ori); // Oops! the first character in stdin is '\n', not '0' '9', and causes scanf failed! cout << ": " << ori << endl; 18

19 Standard I/O in C getchar() read a character from stdin Usage: #include <stdio.h> int getchar( void ); Returns the input character Ex: int c = getchar(); 19

20 Standard I/O in C ungetc() pushes a character back onto a data stream. Usage: #include <stdio.h> int ungetc( int chr, FILE * stream); chr: the character to be pushed stream: the target data stream If successful, it returns chr, otherwise returns EOF (-1) Ex: ungetc( \n, stdin); 20

21 Standard Input in C How to clear the stdin? Method 1: int a=0, b =0, c=0, R=0; R = scanf("%d%d%d", &a, &b, &c); printf("a=%d, b=%d, c=%d and R=%d\n", a, b, c, R); getchar(); // It just clear one character that is kept in stdin Method 2: Method 3: int a=0, b =0, c=0, R=0; R = scanf("%d%d%d", &a, &b, &c); printf("a=%d, b=%d, c=%d and R=%d\n", a, b, c, R); { int c; while((c=getchar())!='\n'&&c!=eof); } //EOF = (-1) /* The best method since it can clear all characters in stdin but needs high computational cost. */ int a=0, b =0, c=0, R=0; R = scanf("%d%d%d", &a, &b, &c); printf("a=%d, b=%d, c=%d and R=%d\n", a, b, c, R); v // Read all characters, except \n, from stdin getchar(); // Read the last \n // Maybe fail in sscanf 21

22 Standard Input in C How to clear the stdin? DO NOT use fflush(stdin) to clear stdin! Since the C standard does not define it. int a=0, b =0, c=0, R=0; R = scanf("%d%d%d", &a, &b, &c); printf("a=%d, b=%d, c=%d and R=%d\n", a, b, c, R); fflush(stdin); 22

23 Standard Input in C sscanf() #include <stdio.h> int sscanf( const char *buffer, const char *format [, argument ]... ); where the buffer is the input string The difference between the scanf and sscanf is that the input buffer of sscanf is an array of characters, not the stdin. Besides the input buffer, the usage of sscanf is the same as scanf 23

24 Standard Output in C++ Let s print some variables #include <stdio.h> int main(){ int x = 10; double y = 1.234; char *s = "Hello world"; printf("%d, %f, %s\n", x, y, s); } #include <iostream> int main(){ int x = 10; double y = 1.234; char *s = "Hello world"; std::cout.precision(7); std::cout << x << ", " << y << ","; std::cout << s << std::endl; } or #include <iostream> using namespace std; int main(){ int x = 10; double y = 1.234; char *s = Hello world ; cout.precision(7); cout << x << ", " << y << ","; cout << s << endl; } 24

25 Standard Output in C++ Namespace Scope operator Left object std::cout << x; Insertion operator (a binary operator) It means that put the x into the stdout cout is an object that represents the stdout Right object To save typing, we can use the using namespace command. std::cout.precision(7); Object Member method Member-selection operator 25

26 Standard Output in C++ The manipulators of cout int x =255; std::cout << std::oct ; std::cout << x << std::endl; // 377 std::cout << std::dec ; std::cout << x << std::endl; // 255 std::cout << std::showbase << std::hex << x << std::endl ; // 0xff std::cout << std::uppercase << x << std::endl ; // 0xFF std::cout << std::noshowbase; std::cout.width(10); std::cout << std::dec << x << std::endl; // 255 std::cout.width(10); std::cout << std::right << x << std::endl; // 255 std::cout.width(10); std::cout << std::left << x << "!" << std::endl; // 255! float y = ; std::cout.precision(5); std::cout << y << std::endl; //

27 Standard Output in C++ The list of manipulators boolalpha - Insert or extract bool objects as "true" or "false". noboolalpha - Insert or extract bool objects as numeric values. fixed - Insert floating-point values in fixed format. scientific - Insert floating-point values in scientific format. internal - Internal-justify. left - Left-justify. right - Right-justify. dec - Insert or extract integer values in decimal format. hex - Insert or extract integer values in hexadecimal (base 16) format. oct - Insert or extract values in octal (base 8) format. 27

28 Standard Output in C++ The list of manipulators noshowbase - Do not prefix value with its base. showbase - Prefix value with its base. noshowpoint - Do not show decimal point if not necessary. showpoint - Always show decimal point when inserting floating-point values. noshowpos - Don't insert plus sign (+) if number >= 0. showpos - Do insert plus sign (+) if number >=0. noskipws - Do not skip initial white space on extracting. skipws - Skip initial white space on extracting. nouppercase - Don't replace lowercase letters by uppercase equivalents. uppercase - Replace lowercase letters by uppercase equivalents. unitbuf - Flush buffer after an insert. nounitbuf - Don't flush buffer after each insert. 28

29 Standard Output in C++ ios::flags setf( long ) and unsetf( long), to set and unset the flag. Using flags() to recover all setting int x =255; long OrgFlag = std::cout.flags(); // Record the origin setting std::cout.unsetf( ios::dec ); // unset std::cout.setf( ios::oct ); std::cout << x << std::endl; // 0377 std::cout.unsetf( ios::oct ); // unset std::cout.setf( ios::dec ); std::cout << x << std::endl; // 255 std::cout.unsetf( ios::dec ); // unset std::cout.setf( ios::hex ios::showbase ios::uppercase ); std::cout << x << std::endl; // 0xFF std::cout.flags( OrgFlag ); std::cout << x << std::endl; // Recover the flag 29

30 Standard Input in C++ std::cin with the extraction operator, >> cin is an object that represents the stdin char c1=0, c2 =0, c3=0; std::cin >> c1 >> c2; std::cout << c1 << ", " << c2 << std::endl; std::cin >> c3; std::cout << c3 << std::endl; Notice that the delimit characters are white space keys.

31 Standard Input in C++ Conversion failure It will stop immediately int x = 10; std::cin >> x; // Try to type xyz\n std::cout << x << std::endl; // 10 The solution is do{ std::cin.clear(); // Clear the last conversion state std::cin >> x ; { int c; while((c=getchar())!='\n'&&c!=eof); } // Clear the input buffer } while( std::cin.fail() ); // Check the conversion state std::cout << x << std::endl;

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Lecture 4 Input & Output Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Outline printf scanf putchar getchar getch getche Input and Output in

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi CE 43 - Fall 97 Lecture 4 Input and Output Department of Computer Engineering Outline printf

More information

Streams - Object input and output in C++

Streams - Object input and output in C++ Streams - Object input and output in C++ Dr. Donald Davendra Ph.D. Department of Computing Science, FEI VSB-TU Ostrava Dr. Donald Davendra Ph.D. (Department of Computing Streams - Object Science, input

More information

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

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University ITC213: STRUCTURED PROGRAMMING Bhaskar Shrestha National College of Computer Studies Tribhuvan University Lecture 07: Data Input and Output Readings: Chapter 4 Input /Output Operations A program needs

More information

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

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 18 I/O in C Standard C Library I/O commands are not included as part of the C language. Instead, they are part of the Standard C Library. A collection of functions and macros that must be implemented

More information

Chapter 12 - C++ Stream Input/Output

Chapter 12 - C++ Stream Input/Output Chapter 12 - C++ Stream Input/Output 1 12.1 Introduction 12.2 Streams 12.2.1 Classic Streams vs. Standard Streams 12.2.2 iostream Library Header Files 12.2.3 Stream Input/Output Classes and Objects 12.3

More information

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

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. C How to Program, 6/e 1992-2010 by Pearson Education, Inc. An important part of the solution to any problem is the presentation of the results. In this chapter, we discuss in depth the formatting features

More information

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

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

More information

THE FUNDAMENTAL DATA TYPES

THE FUNDAMENTAL DATA TYPES THE FUNDAMENTAL DATA TYPES Declarations, Expressions, and Assignments Variables and constants are the objects that a prog. manipulates. All variables must be declared before they can be used. #include

More information

basic_fstream<chart, traits> / \ basic_ifstream<chart, traits> basic_ofstream<chart, traits>

basic_fstream<chart, traits> / \ basic_ifstream<chart, traits> basic_ofstream<chart, traits> The C++ I/O System I/O Class Hierarchy (simplified) ios_base ios / \ istream ostream \ / iostream ifstream fstream ofstream The class ios_base -- public variables and methods The derived classes istream,

More information

Chapter 21 - C++ Stream Input/Output

Chapter 21 - C++ Stream Input/Output Chapter 21 - C++ Stream Input/Output Outline 21.1 Introduction 21.2 Streams 21.2.1 Iostream Library Header Files 21.2.2 Stream Input/Output Classes and Objects 21.3 Stream Output 21.3.1 Stream-Insertion

More information

Lab 6. Review of Variables, Formatting & Loops By: Dr. John Abraham, Professor, UTPA

Lab 6. Review of Variables, Formatting & Loops By: Dr. John Abraham, Professor, UTPA Variables: Lab 6 Review of Variables, Formatting & Loops By: Dr. John Abraham, Professor, UTPA We learned that a variable is a name assigned to the first byte of the necessary memory to store a value.

More information

Introduction to Programming

Introduction to Programming Introduction to Programming Lecture 5: Interaction Interaction Produce output Get input values 2 Interaction Produce output Get input values 3 Printing Printing messages printf("this is message \n"); Printing

More information

Introduction to C++ (Extensions to C)

Introduction to C++ (Extensions to C) Introduction to C++ (Extensions to C) C is purely procedural, with no objects, classes or inheritance. C++ is a hybrid of C with OOP! The most significant extensions to C are: much stronger type checking.

More information

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

The C Programming Language Part 2. (with material from Dr. Bin Ren, William & Mary Computer Science) The C Programming Language Part 2 (with material from Dr. Bin Ren, William & Mary Computer Science) 1 Overview Input/Output Structures and Arrays 2 Basic I/O character-based putchar (c) output getchar

More information

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class C++ IO C++ IO All I/O is in essence, done one character at a time For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Concept: I/O operations act on streams

More information

CS2141 Software Development using C/C++ Stream I/O

CS2141 Software Development using C/C++ Stream I/O CS2141 Software Development using C/C++ Stream I/O iostream Two libraries can be used for input and output: stdio and iostream The iostream library is newer and better: It is object oriented It can make

More information

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

Stream Model of I/O. Basic I/O in C Stream Model of I/O 1 A stream provides a connection between the process that initializes it and an object, such as a file, which may be viewed as a sequence of data. In the simplest view, a stream object

More information

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

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

1/25/2018. ECE 220: Computer Systems & Programming. Write Output Using printf. Use Backslash to Include Special ASCII Characters University of Illinois at Urbana-Champaign Dept. of Electrical and Computer Engineering ECE 220: Computer Systems & Programming Review: Basic I/O in C Allowing Input from the Keyboard, Output to the Monitor

More information

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

INTRODUCTION TO C++ C FORMATTED INPUT/OUTPUT. Dept. of Electronic Engineering, NCHU. Original slides are from INTRODUCTION TO C++ C FORMATTED INPUT/OUTPUT Original slides are from http://sites.google.com/site/progntut/ Dept. of Electronic Engineering, NCHU Outline 2 printf and scanf Streams (input and output)

More information

WARM UP LESSONS BARE BASICS

WARM UP LESSONS BARE BASICS WARM UP LESSONS BARE BASICS CONTENTS Common primitive data types for variables... 2 About standard input / output... 2 More on standard output in C standard... 3 Practice Exercise... 6 About Math Expressions

More information

Chapter 21 - C++ Stream Input/Output

Chapter 21 - C++ Stream Input/Output Chapter 21 - C++ Stream Input/Output Outline 21.1 Introduction 21.2 Streams 21.2.1 Iostream Library Header Files 21.2.2 Stream Input/Output Classes and Objects 21.3 Stream Output 21.3.1 Stream-Insertion

More information

Fundamentals of Programming. Lecture 11: C Characters and Strings

Fundamentals of Programming. Lecture 11: C Characters and Strings 1 Fundamentals of Programming Lecture 11: C Characters and Strings Instructor: Fatemeh Zamani f_zamani@ce.sharif.edu Sharif University of Technology Computer Engineering Department The lectures of this

More information

LESSON 4. The DATA TYPE char

LESSON 4. The DATA TYPE char LESSON 4 This lesson introduces some of the basic ideas involved in character processing. The lesson discusses how characters are stored and manipulated by the C language, how characters can be treated

More information

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

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code CS102: Standard I/O Our next topic is standard input and standard output in C. The adjective "standard" when applied to "input" or "output" could be interpreted to mean "default". Typically, standard output

More information

Module 11 The C++ I/O System

Module 11 The C++ I/O System Table of Contents Module 11 The C++ I/O System CRITICAL SKILL 11.1: Understand I/O streams... 2 CRITICAL SKILL 11.2: Know the I/O class hierarchy... 3 CRITICAL SKILL 11.3: Overload the > operators...

More information

Unit 4. Input/Output Functions

Unit 4. Input/Output Functions Unit 4 Input/Output Functions Introduction to Input/Output Input refers to accepting data while output refers to presenting data. Normally the data is accepted from keyboard and is outputted onto the screen.

More information

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

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 Overview The C Programming Language Part 2 Input/Output Structures and Arrays (with material from Dr. Bin Ren, William & Mary Computer Science) 1 2 character-based putchar (c) output getchar () input formatted

More information

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

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018 C++ Basics Lecture 2 COP 3014 Spring 2018 January 8, 2018 Structure of a C++ Program Sequence of statements, typically grouped into functions. function: a subprogram. a section of a program performing

More information

CSE 12 Spring 2018 Week One, Lecture Two

CSE 12 Spring 2018 Week One, Lecture Two CSE 12 Spring 2018 Week One, Lecture Two Homework One and Two: - Introduction to C - Review of basic programming principles - Building from fgetc and fputc - Input and output strings and numbers - Introduction

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types Programming Fundamentals for Engineers 0702113 5. Basic Data Types Muntaser Abulafi Yacoub Sabatin Omar Qaraeen 1 2 C Data Types Variable definition C has a concept of 'data types' which are used to define

More information

Introduction to Computing Lecture 03: Basic input / output operations

Introduction to Computing Lecture 03: Basic input / output operations Introduction to Computing Lecture 03: Basic input / output operations Assist.Prof.Dr. Nükhet ÖZBEK Ege University Department of Electrical & Electronics Engineering nukhet.ozbek@ege.edu.tr Topics Streams

More information

Chapter 2. Section 2.5 while Loop. CS 50 Hathairat Rattanasook

Chapter 2. Section 2.5 while Loop. CS 50 Hathairat Rattanasook Chapter 2 Section 2.5 while Loop CS 50 Hathairat Rattanasook Loop Iteration means executing a code segment more than once. A loop is an iterative construct. It executes a statement 0..n times while a condition

More information

CSE 12 Spring 2016 Week One, Lecture Two

CSE 12 Spring 2016 Week One, Lecture Two CSE 12 Spring 2016 Week One, Lecture Two Homework One and Two: hw2: Discuss in section today - Introduction to C - Review of basic programming principles - Building from fgetc and fputc - Input and output

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

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

C Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach C Fundamentals & Formatted Input/Output adopted from KNK C Programming : A Modern Approach C Fundamentals 2 Program: Printing a Pun The file name doesn t matter, but the.c extension is often required.

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

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

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 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

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

Input / Output Functions

Input / Output Functions CSE 2421: Systems I Low-Level Programming and Computer Organization Input / Output Functions Presentation G Read/Study: Reek Chapter 15 Gojko Babić 10-03-2018 Input and Output Functions The stdio.h contain

More information

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

printf(%c\n, character); printf(%s\n, This is a string); printf(%s\n, string); printf(%s\n,stringptr); return 0; Chapter 9: Formatted Input/Output ================================= * All input and output is performed with streams - sequences of characters organized into lines. * Each line consists of zero or more

More information

Physics 6720 I/O Methods October 30, C++ and Unix I/O Streams

Physics 6720 I/O Methods October 30, C++ and Unix I/O Streams Physics 6720 I/O Methods October 30, 2002 We have been using cin and cout to handle input from the keyboard and output to the screen. In these notes we discuss further useful capabilities of these standard

More information

Getting started with C++ (Part 2)

Getting started with C++ (Part 2) Getting started with C++ (Part 2) CS427: Elements of Software Engineering Lecture 2.2 11am, 16 Jan 2012 CS427 Getting started with C++ (Part 2) 1/22 Outline 1 Recall from last week... 2 Recall: Output

More information

PROGRAMMING IN C++ KAUSIK DATTA 18-Oct-2017

PROGRAMMING IN C++ KAUSIK DATTA 18-Oct-2017 PROGRAMMING IN C++ KAUSIK DATTA 18-Oct-2017 Objectives Recap C Differences between C and C++ IO Variable Declaration Standard Library Introduction of C++ Feature : Class Programming in C++ 2 Recap C Built

More information

Should you know scanf and printf?

Should you know scanf and printf? C-LANGUAGE INPUT & OUTPUT C-Language Output with printf Input with scanf and gets_s and Defensive Programming Copyright 2016 Dan McElroy Should you know scanf and printf? scanf is only useful in the C-language,

More information

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

File Handling in C. EECS 2031 Fall October 27, 2014 File Handling in C EECS 2031 Fall 2014 October 27, 2014 1 Reading from and writing to files in C l stdio.h contains several functions that allow us to read from and write to files l Their names typically

More information

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

CMPT 102 Introduction to Scientific Computer Programming. Input and Output. Your first program 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

More information

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2 Control Structures for C CS Basics 10) C Control Structures Emmanuel Benoist Fall Term 2016-17 Data Input and Output Single character In and Output Writing output data Control Statements Branching Looping

More information

Fig: iostream class hierarchy

Fig: iostream class hierarchy Unit 6: C++ IO Systems ================== Streams: Θ A stream is a logical device that either produces or consumes information. Θ A stream is linked to a physical device by the I/O system. Θ All streams

More information

Introduction to Computer and Program Design. Lesson 8 C++ James C.C. Cheng Department of Computer Science National Chiao Tung University

Introduction to Computer and Program Design. Lesson 8 C++ James C.C. Cheng Department of Computer Science National Chiao Tung University Introduction to Computer and Program Design Lesson 8 C++ James C.C. Cheng Department of Computer Science National Chiao Tung University Textbooks l C++ Primer, 5ed By Stanley B. Lippman, Josée Lajoie,

More information

A First Program - Greeting.cpp

A First Program - Greeting.cpp C++ Basics A First Program - Greeting.cpp Preprocessor directives Function named main() indicates start of program // Program: Display greetings #include using namespace std; int main() { cout

More information

Computers Programming Course 5. Iulian Năstac

Computers Programming Course 5. Iulian Năstac Computers Programming Course 5 Iulian Năstac Recap from previous course Classification of the programming languages High level (Ada, Pascal, Fortran, etc.) programming languages with strong abstraction

More information

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords. Chapter 1 File Extensions: Source code (cpp), Object code (obj), and Executable code (exe). Preprocessor processes directives and produces modified source Compiler takes modified source and produces object

More information

! A literal represents a constant value used in a. ! Numbers: 0, 34, , -1.8e12, etc. ! Characters: 'A', 'z', '!', '5', etc.

! A literal represents a constant value used in a. ! Numbers: 0, 34, , -1.8e12, etc. ! Characters: 'A', 'z', '!', '5', etc. Week 1: Introduction to C++ Gaddis: Chapter 2 (excluding 2.1, 2.11, 2.14) CS 1428 Fall 2014 Jill Seaman Literals A literal represents a constant value used in a program statement. Numbers: 0, 34, 3.14159,

More information

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering Lecture 3 Winter 2011/12 Oct 25 Visual C++: Problems and Solutions New section on web page (scroll down)

More information

LAB 4 Extending Signed and Unsigned Numbers

LAB 4 Extending Signed and Unsigned Numbers LAB 4 Extending Signed and Unsigned Numbers Objective: Explain unsigned and signed numbers, zero extension and sign extension, and variable declarations. The 80x86 provides several instructions that will

More information

Basic Types and Formatted I/O

Basic Types and Formatted I/O Basic Types and Formatted I/O C Variables Names (1) Variable Names Names may contain letters, digits and underscores The first character must be a letter or an underscore. the underscore can be used but

More information

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING Dr. Shady Yehia Elmashad Outline 1. Introduction to C++ Programming 2. Comment 3. Variables and Constants 4. Basic C++ Data Types 5. Simple Program: Printing

More information

Standard File Pointers

Standard File Pointers 1 Programming in C Standard File Pointers Assigned to console unless redirected Standard input = stdin Used by scan function Can be redirected: cmd < input-file Standard output = stdout Used by printf

More information

UEE1303(1070) S 12 Object-Oriented Programming in C++

UEE1303(1070) S 12 Object-Oriented Programming in C++ Computational Intelligence on Automation Lab @ NCTU Learning Objectives UEE1303(1070) S 12 Object-Oriented Programming in C++ Lecture 06: Streams and File Input/Output I/O stream istream and ostream member

More information

Objects and streams and files CS427: Elements of Software Engineering

Objects and streams and files CS427: Elements of Software Engineering Objects and streams and files CS427: Elements of Software Engineering Lecture 6.2 (C++) 10am, 13 Feb 2012 CS427 Objects and streams and files 1/18 Today s topics 1 Recall...... Dynamic Memory Allocation...

More information

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski) THE INTEGER DATA TYPES STORAGE OF INTEGER TYPES IN MEMORY All data types are stored in binary in memory. The type that you give a value indicates to the machine what encoding to use to store the data in

More information

Reserved Words and Identifiers

Reserved Words and Identifiers 1 Programming in C Reserved Words and Identifiers Reserved word Word that has a specific meaning in C Ex: int, return Identifier Word used to name and refer to a data element or object manipulated by the

More information

LECTURE 02 INTRODUCTION TO C++

LECTURE 02 INTRODUCTION TO C++ PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 02 INTRODUCTION

More information

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14 C introduction Variables Variables 1 / 14 Contents Variables Data types Variable I/O Variables 2 / 14 Usage Declaration: t y p e i d e n t i f i e r ; Assignment: i d e n t i f i e r = v a l u e ; Definition

More information

Input/output functions

Input/output functions Computer Programming Input/output functions Marius Minea marius@cs.upt.ro 6 November 2017 All inputs must be checked! A program will not always receive the data it asks for User may make mistakes, or may

More information

Chapter 8 C Characters and Strings

Chapter 8 C Characters and Strings Chapter 8 C Characters and Strings Objectives of This Chapter To use the functions of the character handling library (). To use the string conversion functions of the general utilities library

More information

Engineering Problem Solving with C++, Etter/Ingber

Engineering Problem Solving with C++, Etter/Ingber Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs C++, Second Edition, J. Ingber 1 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input

More information

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

C Concepts - I/O. Lecture 19 COP 3014 Fall November 29, 2017 C Concepts - I/O Lecture 19 COP 3014 Fall 2017 November 29, 2017 C vs. C++: Some important differences C has been around since around 1970 (or before) C++ was based on the C language While C is not actually

More information

Jan 27, C++ STL Streams. Daniel Maleike

Jan 27, C++ STL Streams. Daniel Maleike C++ STL Streams Why Stream-IO? The STL way for I/O Input, output, formatting, file access More type-safe than printf(), scanf() Extensible with user defined types (classes) Inheritable, i.e. custom I/O

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

BITG 1233: Introduction to C++

BITG 1233: Introduction to C++ BITG 1233: Introduction to C++ 1 Learning Outcomes At the end of this lecture, you should be able to: Identify basic structure of C++ program (pg 3) Describe the concepts of : Character set. (pg 11) Token

More information

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

Binghamton University. CS-211 Fall Input and Output. Streams and Stream IO Input and Output Streams and Stream IO 1 Standard Input and Output Need: #include Large list of input and output functions to: Read and write from a stream Open a file and make a stream Close

More information

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program Overview - General Data Types - Categories of Words - The Three S s - Define Before Use - End of Statement - My First Program a description of data, defining a set of valid values and operations List of

More information

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

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments File I/O Content Input Output Devices File access Function of File I/O Redirection Command-line arguments UNIX and C language C is a general-purpose, high-level language that was originally developed by

More information

String Variables and Output/Input. Adding Strings and Literals to Your Programming Skills and output/input formatting

String Variables and Output/Input. Adding Strings and Literals to Your Programming Skills and output/input formatting String Variables and Output/Input Adding Strings and Literals to Your Programming Skills and output/input formatting A group of characters put together to create text is called a string. Strings are one

More information

Console Input and Output

Console Input and Output Console Input and Output Hour 5 PObjectives

More information

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

Binghamton University. CS-211 Fall Input and Output. Streams and Stream IO Input and Output Streams and Stream IO 1 Standard Input and Output Need: #include Large list of input and output functions to: Read and write from a stream Open a file and make a stream Close

More information

Course organization. Course introduction ( Week 1)

Course organization. Course introduction ( Week 1) Course organization Course introduction ( Week 1) Code editor: Emacs Part I: Introduction to C programming language (Week 2-9) Chapter 1: Overall Introduction (Week 1-3) Chapter 2: Types, operators and

More information

Fundamentals of Programming CS-110. Lecture 2

Fundamentals of Programming CS-110. Lecture 2 Fundamentals of Programming CS-110 Lecture 2 Last Lab // Example program #include using namespace std; int main() { cout

More information

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program? Intro to Programming & C++ Unit 1 Sections 1.1-4 and 2.1-10, 2.12-13, 2.15-17 CS 1428 Spring 2019 Jill Seaman 1.1 Why Program? Computer programmable machine designed to follow instructions Program a set

More information

CSC 1107: Structured Programming

CSC 1107: Structured Programming CSC 1107: Structured Programming J. Kizito Makerere University e-mail: www: materials: e-learning environment: office: alt. office: jkizito@cis.mak.ac.ug http://serval.ug/~jona http://serval.ug/~jona/materials/csc1107

More information

Exercise 1.1 Hello world

Exercise 1.1 Hello world Exercise 1.1 Hello world The goal of this exercise is to verify that computer and compiler setup are functioning correctly. To verify that your setup runs fine, compile and run the hello world example

More information

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

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

Data Input and Output 187

Data Input and Output 187 Chapter 7 DATA INPUT AND OUTPUT LEARNING OBJECTIVES After reading this chapter, the readers will be able to understand input and output concepts as they apply to C programs. use different input and output

More information

Number Systems, Scalar Types, and Input and Output

Number Systems, Scalar Types, and Input and Output Number Systems, Scalar Types, and Input and Output Outline: Binary, Octal, Hexadecimal, and Decimal Numbers Character Set Comments Declaration Data Types and Constants Integral Data Types Floating-Point

More information

CS2141 Software Development using C/C++ C++ Basics

CS2141 Software Development using C/C++ C++ Basics CS2141 Software Development using C/C++ C++ Basics Integers Basic Types Can be short, long, or just plain int C++ does not define the size of them other than short

More information

CSC 1107: Structured Programming

CSC 1107: Structured Programming CSC 1107: Structured Programming J. Kizito Makerere University e-mail: www: materials: e-learning environment: office: jkizito@cis.mak.ac.ug http://serval.ug/~jona http://serval.ug/~jona/materials/csc1107

More information

UNIT-I Input/ Output functions and other library functions

UNIT-I Input/ Output functions and other library functions Input and Output functions UNIT-I Input/ Output functions and other library functions All the input/output operations are carried out through function calls. There exists several functions that become

More information

Chapter 2: Introduction to C++

Chapter 2: Introduction to C++ Chapter 2: Introduction to C++ Copyright 2010 Pearson Education, Inc. Copyright Publishing as 2010 Pearson Pearson Addison-Wesley Education, Inc. Publishing as Pearson Addison-Wesley 2.1 Parts of a C++

More information

Chapter 7. Basic Types

Chapter 7. Basic Types Chapter 7 Basic Types Dr. D. J. Jackson Lecture 7-1 Basic Types C s basic (built-in) types: Integer types, including long integers, short integers, and unsigned integers Floating types (float, double,

More information

The detail of sea.c [1] #include <stdio.h> The preprocessor inserts the header file stdio.h at the point.

The detail of sea.c [1] #include <stdio.h> The preprocessor inserts the header file stdio.h at the point. Chapter 1. An Overview 1.1 Programming and Preparation Operating systems : A collection of special programs Management of machine resources Text editor and C compiler C codes in text file. Source code

More information

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Copyright 2009 Publishing Pearson as Pearson Education, Addison-Wesley Inc. Publishing as Pearson Addison-Wesley

More information

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University Fundamental Data Types CSE 130: Introduction to Programming in C Stony Brook University Program Organization in C The C System C consists of several parts: The C language The preprocessor The compiler

More information

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

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

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

Pointers cause EVERYBODY problems at some time or another. char x[10] or char y[8][10] or char z[9][9][9] etc. Compound Statements So far, we ve mentioned statements or expressions, often we want to perform several in an selection or repetition. In those cases we group statements with braces: i.e. statement; statement;

More information