cs 161 introduction to programming and problem solving chapter 13 console io herbert g. mayer, psu...

25
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 ECE 103 material by prof. Phillip Wong @ PSU

Upload: rudolph-richardson

Post on 23-Dec-2015

219 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: 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

CS 161Introduction to Programming

and Problem Solving

Chapter 13Console IO

Herbert G. Mayer, PSUStatus 9/8/2014

Initial content copied verbatim fromECE 103 material by prof. Phillip Wong @ PSU

Page 2: 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

Syllabus Console I/O Output Functions Input Examples

Page 3: 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

3

Common Console I/O Functions

The C++ standard and streamio libraries contain functions to print output to and read input from the console

“Console” refers to: Output device (e.g., monitor or output stream) Input device (e.g., keyboard or input stream)

The <stdio.h> header file contains prototypes for the console I/O functions

#include <stdio.h>

Page 4: 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

4

Output Functions

int putchar( int c ); putchar() writes a character c to the console If successful, the character written is returned.

If not successful, the EOF value is returned

Note: EOF is a pre-defined macro

The expected argument c is of type integer. If c is type char, it is converted to an integer first

Make sure no integer of value > 255 is passed! Best to pass a char literal or char type object

Page 5: 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

5

Example:

#include <stdio.h> // old fashioned Cint main( void ){ // main

int x = 'e';char y = 's';

putchar( 'Y' ); // output: ‘Y’putchar( x ); // ouptut: ‘e’putchar( y ); // output: ‘s’putchar( 33 ); // 33 is '!' in ASCII

return 0;} //end main

Output:

!

Page 6: 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

6

int printf( const char * format, … ); printf() writes formatted output to the console You have already learned cin and cout If successful, the number of characters written is

returned; else a negative value is returned, indicating error!

format is a string that contains any combination of literal text and conversion specifiers

… is an optional argument list of expressions whose values are to be printed

For each item in the list, there must be a corresponding conversion specifier in format

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

7

A conversion specifier inside printf() string: Begins with % Ends with a conversion character Unix has pretty incomplete printf man-page

Between the % and the conversion character are optional formatting values (in this order): – to left-justify output (default is right-justify) + to force display of + or – sign Number that specifies a minimum field width . (period), which separates field width from precision Number that specifies the precision

(# of digits printed after a decimal point)

Page 8: 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

8

Variable Type printf() Specifier Comment

Integer Values

short, int %d, %i

long %ld, %li

int %u unsigned

int %x, %X hexadecimal

Floating-Point Values

float, double %f%e, %E%g, %G

fixed decimal formatscientific notationshorter of %f or %e

long double %Lf,%Le, %LE%Lg, %LG

Character & String Values

char %c

char * %s string

Miscellaneous

address %p memory address

To print % symbol % %

Page 9: 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

9

An escape sequence embedded in the format string performs special actions

A sequence starts with the '\' character

Sequence Description Sequence Description\a alert (bell) character \v vertical tab

\b backspace \\ backslash

\f formfeed \' single quote

\n newline \" double quote

\r carriage return

\t horizontal tab \xhh hexadecimal number

Page 10: 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

10

Example:

#include <stdio.h>int main( void ){ // main

printf("Wake up!\n");

printf("\n"); /* Blank */

printf("Summer ");printf("is coming.\n");

printf(" See \"you\"\nlater.\n");return 0;

} //end main

Wake up!

Summer is coming. See "you"later.

Page 11: 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

11

Example:

#include <stdio.h>int main( void ){ // main

int c = 65; // an ’A’char ch = 'B'; // obvious

printf( "c = %c\n", c );printf( "c = %d\n", c );printf( "ch = %c\n", ch );printf( "ch = %d\n", ch );

return 0;} //end main

c = Ac = 65ch = Bch = 66

Page 12: 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

12

Example:

#include <stdio.h>int main( void ){ // main

int x = 5, y = 9;

printf( "%d ", 12 );printf( "[%d]\n", 3*x+y );printf( "x equals %d\n", x );printf( "x=%d y=%d\n", x, y );printf( "x=%3d y=%3d\n", x, y );printf( "x=%3d y=%3d\n", 12, 7 );return 0;

} //end main

12 [24]x equals 5x=5 y=9x= 5 y= 9x= 12 y= 7

Page 13: 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

13

Example:#include <stdio.h>int main( void ){ // main

float u = 5.0;double v = 1.75;const char * str = "PSU rocks!";

printf( "%c %d %f\n", 65, 65, (float)65 );printf( "%f\n", 2/3.0 );printf( "u=[%f] v=[%f]\n", u, v );printf( "%.1f %.2f %.3f\n", v, v, v );printf( "%12.3f\n", v );printf( "%12.3e\n", 254*v );printf( "%s\n", str );printf( "[%15s]\n", str );printf( "[%-15s]\n", str );return 0;

} //end main

A 65 65.0000000.666667u=[5.000000] v=[1.750000]1.8 1.75 1.750 1.750 4.445e+02PSU rocks![ PSU rocks!][PSU rocks! ]

Page 14: 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

14

Example:#include <stdio.h>#define V1 1.0#define V2 1.5e-7#define V3 1.5e7

int main( void ){ // main

printf( "V1 (%%.8f) = %.8f\n", V1 );printf( "V1 (%%.8g) = %.8g\n", V1 ); // %g is shorter of: %f and %eprintf( "V1 (%%.8e) = %.8e\n\n", V1 );

printf( "V2 (%%.8f) = %.8f\n", V2 );printf( "V2 (%%.8g) = %.8g\n", V2 ); // %g is shorter of: %f and %eprintf( "V2 (%%.8e) = %.8e\n\n", V2 );

printf( "V3 (%%.8f) = %.8f\n", V3 );printf( "V3 (%%.8g) = %.8g\n", V3 ); // %g is shorter of: %f and %eprintf( "V3 (%%.8e) = %.8e\n", V3 );return 0;

} //end main

V1 (%.8f) = 1.00000000V1 (%.8g) = 1V1 (%.8e) = 1.00000000e+00

V2 (%.8f) = 0.00000015V2 (%.8g) = 1.5e-07V2 (%.8e) = 1.50000000e-07

V3 (%.8f) = 15000000.00000000V3 (%.8g) = 15000000V3 (%.8e) = 1.50000000e+07

Page 15: 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

15

Input Functions

int getchar( void ); getchar() reads a single character from the console If successful, the next character from the console is

read and returned, converted to int If not successful, the EOF value is returned

Page 16: 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

16

Example:

#include <stdio.h>int main( void ){ // main

int ch;

printf( "Enter character: ” );ch = getchar();

printf( "ch = %c\n", ch );return 0;

} //end main

Enter character: Ach = A

Page 17: 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

17

Example:

#include <stdio.h>int main( void ){ // main

int ch1, ch2;

printf( "Enter ch1: ” );ch1 = getchar();printf( "Enter ch2: ” );ch2 = getchar();

printf( "ch1 = %c ch2 = %c\n", ch1, ch2 );return 0;

} //end main

Enter ch1: AEnter ch2: ch1 = A ch2 =

Why does this look wrong?

Page 18: 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

18

getchar() works with buffered line input:

Buffer contents after pressing 'A' and 'Enter':

ch1=getchar() gets the 'A' for ch1

After reading the first character in the buffer, the "next character" arrow is updated:

ch2=getchar() gets the '\n' for ch2

'A' '\n'

'A' '\n'

Arrow indicates "next character" to read.

Page 19: 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

19

A workaround for the buffer problem:

#include <stdio.h>int main( void ){ // main

int ch1, ch2;

printf( "Enter ch1: " );ch1 = getchar();getchar(); // Remove pending '\n’printf( "Enter ch2: " );ch2 = getchar();

printf( "ch1 = %c ch2 = %c\n", ch1, ch2 );return 0;

} //end main

Enter ch1: AEnter ch2: Bch1 = A ch2 = B

Page 20: 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

20

int scanf( const char * format, … ); scanf() reads formatted input from the console If successful, the number of items read is returned If not successful, EOF is returned, -1 on Unix

format is a string that contains any combination of conversion specifiers

… is an optional argument list of variable addresses where the input values are to be stored

For each item in the list, there must be a corresponding conversion specifier in format

Page 21: 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

21

The “address” of a variable is the memory location that holds the variable's value

The & character is C’s “address-of” operator

When storing the value read by scanf(), you must specify the address of the variable that will receive the value

Example: int x; ... scanf( "%d", &x );

1. Read character string of digits ‘0’..‘9’ into the input buffer; only ‘0’..’9’ due to %d2. Convert the string value to an integer3. Store the value at the address of int variable x

Page 22: 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

22

Variable Type scanf() Specifier

Integer Values

int %d, %i

short %hd, %hi

long int %ld, %li

unsigned int %u

Floating-Point Values

float %f, %e, %E, %g, %G

double %lf, %le, %lE, %lg, %lG

long double %Lf, %Le, %LE, %Lg, %LG

Character Values

char %c

Character String (whitespace delimited – not full text)

char * %s

Page 23: 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

23

Example:

#include <stdio.h>int main( void ){ // main

char cvar;int ivar;float fvar, fv2;double dvar;

scanf( "%c", &cvar );scanf( "%f", &fvar ); /* Use %f for floats */scanf( "%lf", &dvar ); /* Use %lf for doubles */scanf( "%d %f %f", &ivar, &fvar, &fv2 );return 0;

} //end main

Page 24: 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

24

Example: Common error – missing & in scanf()// source file: test.c#include <stdio.h>int main( void ){ // main

int x; // OK to leave uninitializedprintf( "Enter x: ” );scanf( "%d", x );printf( "%d\n", x );return 0;

} //end main

Notice x instead of &x

$ gcc -ansi -Wall -pedantic test.ctest.c: In function 'main':test.c:7: warning: format argument is not a pointer (arg 2)test.c:7: warning: format argument is not a pointer (arg 2)

$ ./a.outEnter x: 45Segmentation fault (core dumped)

Page 25: 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

25

Reminder for printf and scanf Specifiers

Output → If value to display with printf is of type: int : %d long int : %ld float, double : %f %e %g long double : %Lf %Le %Lg

Input → If value to input with scanf is of type: int : %d long int : %ld float : %f %e %g double : %lf %le %lg long double : %Lf %Le %Lg

printf uses the same specifiers for both float and double types.

scanf uses separate specifiers for the float and double types.