80 likes | 183 Views
This guide covers essential techniques for managing input and buffering in C programming. It explains how input is read from buffers, the behavior of end-of-file (EOF), and how to manage character input robustly. With practical examples, it shows how to ensure valid input, handle EOF conditions, and redirect standard input/output from files. Key functions like getchar() and scanf() are discussed, along with tips for maintaining program stability and providing users with opportunities to correct input errors.
E N D
Buffering • C input is read from a buffer • When the buffer is empty, • Characters are moved into it • For terminal, buffer is filled with a line • For a file, buffer is filled with a disk “block” • When no more data is available • EOF (end-of-file) is indicated
getchar() • Removes a character from the buffer • Refilling the buffer, if necessary • Returns the character as an integer • With EOF indicating end-of-file
Robust programming • Make sure the input is valid • If something is wrong, • Give another chance • Handle end-of-file • And missing files • Don’t bomb
Skipping to the end of line • Getting to a new line • Provides a good starting point while((ch=getchar()) && ch != ’\n’) process character while((ch=getchar()) && ch != ’\n’ && ch != EOF) process character
Testing input with scanf() • scanf returns the number of items read • Be sure that it does! if (scanf(”%d”, &x) != 1) something is wrong • It might be better to • Only read one item per scanf • Skip to the end-of-line for a fresh start • And give a second chance at input
Redirection • Unix and DOS allows terminal I/O from files • cprog < file.in • Standard input read from file.in • cprog > file.out • Standard output written to file.out
End-of-file on terminal • On Unix • Type a Ctrl+D • The ASCII EOT (end of transmission) • On DOS and Windows • Type a Ctrl+Z • Descends from pre-Unix DEC operating systems • Stored as the last character of a file • Not a character read by the program