Lecture 2: Character Input/Output in COverview of Today’s LectureEcho 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 LetterDeterministic Finite AutomatonImplementation SkeletonImplementationComplete ImplementationRunning Code on ItselfOK, That’s a B+Improvement: Names for StatesSlide 31Improvement: ModularitySlide 33Slide 34Improvement: Defensive ProgrammingPutting it Together: An “A” EffortSlide 37Slide 38Review of Example #3Another DFA ExampleYet Another DFA ExampleConclusions1Lecture 2:Character Input/Output in CProfessor Jennifer RexfordCOS 217http://www.cs.princeton.edu/courses/archive/spring08/cos217/2Overview of Today’s Lecture •Goals of the lectureImportant C constructs–Program flow (if/else, loops, and switch)–Character input/output (getchar and putchar)Deterministic finite automata (i.e., state machine)Expectations for programming assignments•C programming examplesEcho the input directly to the outputPut all lower-case letters in upper casePut the first letter of each word in upper case•Glossing over some details related to “pointers”… which will be covered in the next lecture3Echo Input Directly to Output•Including the Standard Input/Output (stdio) libraryMakes names of functions, variables, and macros available#include <stdio.h>•Defining procedure main()Starting point of the program, a standard boilerplateint main(void)int main(int argc, char **argv)Hand-waving: argc and argv are for input arguments•Read a single characterReturns a single character from the text stream “standard in” (stdin)c = getchar();•Write a single characterWrites a single character to “standard out” (stdout)putchar(c);4Why a return value?Why an “int”?Putting it All Together#include <stdio.h>int main(void) { int c; c = getchar(); putchar(c); return 0;}5Why is the Character an “int”•Meaning of a data typeDetermines the size of a variable… and how it is interpreted and manipulated•Difference between char and intchar: character, a single byte (256 different values)int: integer, machine-dependent (e.g., -32,768 to 32,767)•One byte is just not big enoughNeed to be able to store any character… plus, special value like End-Of-File (typically “-1”)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)Three arguments: initialization, condition, and re-initializationE.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 loopSimply leave the arguments blankE.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)EOF is a special global constant, defined in stdioThe 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/OIncluding stdio.hFunctions getchar() and putchar()Representation of a character as an integerPredefined constant EOF•Program control flowThe for loop and while loopThe break statementThe return statement•Assignment and comparisonAssignment: “=” Increment: “i++”Comparing for equality “==”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: repeat read a character if it’s lower-case, convert to upper-case write the character until end-of-file12ASCIIAmerican Standard Code for Information Interchange 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 NUL SOH STX ETX EOT ENQ ACK BEL BS HT LF VT FF CR SO SI 16 DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC FS GS RS US 32 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 O 80 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 o 112 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 areCleanReadableMaintainable•It’s not enough that your program works!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;}Avoid Mysterious NumbersCorrect, but ugly to have all these hard-wired constants in the program.16#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)NAME ctype, isdigit, isxdigit, islower, isupper, isalpha, isalnum, isspace, iscntrl, ispunct, isprint, isgraph, isascii - character handlingSYNOPSIS #include <ctype.h> int isalpha(int c); int
View Full Document