Lecture 2: Character Input/Output in COverview of Today’s Lecture Echo Input Directly to OutputPutting it All TogetherWhy is the Character an “int”Read and Write Ten CharactersRead and Write ForeverRead and Write Till End-Of-FileMany Ways to Say the Same ThingReview of Example #1Example #2: Convert Upper CaseASCIIImplementation in CThat’s a B-minusAvoid Mysterious NumbersImprovement: Character LiteralsImprovement: Existing LibrariesUsing the ctype LibraryCompiling and RunningRun the Code on ItselfOutput RedirectionReview of Example #2Example #3: Capitalize First LetterImplementation SkeletonImplementationComplete ImplementationRunning Code on ItselfOK, That’s a B+Improvement: Names for StatesImprovement: Names for StatesImprovement: ModularityImprovement: ModularityImprovement: ModularityImprovement: Defensive ProgrammingPutting it Together: An “A” EffortPutting it Together: An “A” EffortPutting it Together: An “A” EffortReview of Example #31Lecture 2:Character Input/Output in CProf. David AugustCOS 217http://www.cs.princeton.edu/courses/archive/fall07/cos217/2Overview of Today’s Lecture • Goals of the lectureo Important C constructs– Program flow (if/else, loops, and switch)– Character input/output (getchar and putchar)o Deterministic finite automata (i.e., state machine)o Expectations for programming assignments• C programming exampleso Echo the input directly to the outputo Put all lower-case letters in upper caseo Put the first letter of each word in upper case• Glossing over some details related to “pointers”o … which will be covered in the next lecture3Echo Input Directly to Output• Including the Standard Input/Output (stdio) libraryo Makes names of functions, variables, and macros availableo #include <stdio.h>• Defining procedure main()o Starting point of the program, a standard boilerplateo int main(void)o int main(int argc, char **argv)o Hand-waving: argc and argv are for input arguments• Read a single charactero Returns a single character from the text stream “standard in” (stdin)o c = getchar();• Write a single charactero Writes a single character to “standard out” (stdout)o putchar(c);4Why a return value?Why an “int”?#include <stdio.h>int main(void) {int c;c = getchar();putchar(c);return 0;}Putting it All Together5Why is the Character an “int”• Meaning of a data typeo Determines the size of a variableo … and how it is interpreted and manipulated• Difference between char and into char: character, a single byteo int: integer, machine-dependent (e.g., -32,768 to 32,767)• One byte is just not big enougho Need to be able to store any charactero … plus, special value like End-Of-File (typically “-1”)o We’ll see an example with EOF in a few slides6Read and Write Ten Characters• Loop to repeat a set of lines (e.g., for loop)o Three arguments: initialization, condition, and re-initializationo E.g., start at 0, test for less than 10, and increment per iteration#include <stdio.h>int main(void) {int c, i;for (i=0; i<10; i++) {c = getchar();putchar(c);}return 0;}7Read and Write Forever• Infinite for loopo Simply leave the arguments blanko E.g., for ( ; ; ) #include <stdio.h>int main(void) {int c;for ( ; ; ) {c = getchar();putchar(c);}return 0;}8Read and Write Till End-Of-File• Test for end-of-file (EOF)o EOF is a special global constant, defined in stdioo The break statement jumps out of the current scope#include <stdio.h>int main(void) {int c;for ( ; ; ) {c = getchar();if (c == EOF) break;putchar(c);}return 0;}do some stuffdone yet? before the loopdo more stuffafter the loop9Many Ways to Say the Same Thingfor (;;) {c = getchar();if (c == EOF)break;putchar(c);}for (c=getchar(); c!=EOF; c=getchar()) putchar(c);while ((c=getchar())!=EOF)putchar(c);Very typical idiom in C,but messy side-effects in loop testc = getchar();while (c!=EOF) {putchar(c);c = getchar();}10Review of Example #1• Character I/Oo Including stdio.ho Functions getchar() and putchar()o Representation of a character as an integero Predefined constant EOF• Program control flowo The for loop and while loopo The break statemento The return statement• Assignment and comparisono Assignment: “=”o Increment: “i++”o Comparing for equality “==”o Comparing for inequality “!=”11Example #2: Convert Upper Case• Problem: write a program to convert a file to all upper-case(leave nonalphabetic characters alone)• Program design:repeatread a characterif it’s lower-case, convert to upper-casewrite the characteruntil end-of-file12ASCIIAmerican Standard Code for Information Interchange0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 150 NUL SOH STX ETX EOT ENQ ACK BEL BS HT LF VT FF CR SO SI16 DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC FS GS RS US32 SP ! " # $ % & ' ( ) * + , - . /48 0 1 2 3 4 5 6 7 8 9 : ; < = > ?64 @ A B C D E F G H I J K L M N O80 P Q R S T U V W X Y Z [ \ ] ^ _ 96 ` a b c d e f g h i j k l m n o112 p q r s t u v w x y z { | } ~ DEL Lower case: 97-122 and upper case: 65-90E.g., ‘a’ is 97 and ‘A’ is 65 (i.e., 32 apart)13#include <stdio.h>int main(void) {int c;for ( ; ; ) {c = getchar();if (c == EOF) break;if ((c >= 97) && (c < 123))c -= 32;putchar(c);}return 0;}Implementation in C14That’s a B-minus• Programming well means programs that areo Cleano Readableo Maintainable• It’s not enough that your program works!o We take this seriously in COS 217.15#include <stdio.h>int main(void) {int c;for ( ; ; ) {c = getchar();if (c == EOF) break;if ((c >= 97) && (c < 123))c -= 32;putchar(c);}return 0;}Correct, but ugly to have all these hard-wired constants in the program.Avoid Mysterious Numbers16#include <stdio.h>int main(void) {int c;for ( ; ; ) {c = getchar();if (c == EOF) break;if ((c >= ’a’) && (c <= ’z’))c += ’A’ - ’a’;putchar(c);}return 0;}Improvement: Character Literals17Standard C Library Functions ctype(3C)NAMEctype, isdigit, isxdigit, islower, isupper, isalpha, isalnum, isspace, iscntrl, ispunct, isprint, isgraph, isascii - character handlingSYNOPSIS#include <ctype.h>int isalpha(int c);int isupper(int c);int islower(int c);int isdigit(int c);int isalnum(int c);int isspace(int c);int ispunct(int c);int isprint(int c);int isgraph(int c);int
View Full Document