DOC PREVIEW
Princeton COS 217 - Character Input/Output in C

This preview shows page 1-2-3-20-21-40-41-42 out of 42 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 42 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 42 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 42 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 42 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 42 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 42 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 42 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 42 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 42 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

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 lectureImportant 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 examplesEcho the input directly to the outputPut all lower-case letters in upper casePut 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) libraryMakes names of functions, variables, and macros available#include <stdio.h>•Defining procedure main()Starting point of the program, a standard boilerplateint main(void)int main(int argc, char **argv)Hand-waving: argc and argv are for input arguments•Read a single characterReturns a single character from the text stream “standard in” (stdin)c = getchar();•Write a single characterWrites 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 typeDetermines the size of a variable… and how it is interpreted and manipulated•Difference between char and intchar: character, a single byte (256 different values)int: integer, machine-dependent (e.g., -32,768 to 32,767)•One byte is just not big enoughNeed 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-initialization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 loopSimply leave the arguments blank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)EOF is a special global constant, defined in stdio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/OIncluding stdio.hFunctions getchar() and putchar()Representation of a character as an integerPredefined constant EOF•Program control flowThe for loop and while loopThe break statementThe return statement•Assignment and comparisonAssignment: “=” 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 areCleanReadableMaintainable•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

Princeton COS 217 - Character Input/Output in C

Documents in this Course
Summary

Summary

4 pages

Lecture

Lecture

4 pages

Generics

Generics

14 pages

Generics

Generics

16 pages

Lecture

Lecture

20 pages

Debugging

Debugging

35 pages

Types

Types

7 pages

Lecture

Lecture

21 pages

Assembler

Assembler

16 pages

Lecture

Lecture

20 pages

Lecture

Lecture

39 pages

Testing

Testing

44 pages

Pipeline

Pipeline

19 pages

Lecture

Lecture

6 pages

Signals

Signals

67 pages

Building

Building

17 pages

Lecture

Lecture

7 pages

Modules

Modules

12 pages

Generics

Generics

16 pages

Testing

Testing

22 pages

Signals

Signals

34 pages

Lecture

Lecture

19 pages

Load more
Download Character Input/Output in C
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Character Input/Output in C and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Character Input/Output in C 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?