Path: utzoo!utgpu!watmath!iuvax!rutgers!usc!venera.isi.edu!lmiller From: lmiller@venera.isi.edu (Larry Miller) Newsgroups: comp.lang.pascal Subject: Re: file windows (was Re: Standard Pascal) Summary: C Uses ungetc--which is uglier? Message-ID: <9069@venera.isi.edu> Date: 26 Jul 89 18:07:01 GMT References: <8616@pyr.gatech.EDU> <18965@paris.ics.uci.edu> <4623@freja.diku.dk> <2929@virginia.acc.virginia.edu> Reply-To: lmiller@venera.isi.edu.UUCP (Larry Miller) Organization: Information Sciences Institute, Univ. of So. California Lines: 76 In article <2929@virginia.acc.virginia.edu> scl@virginia.acc.Virginia.EDU (Steve Losen) writes: >In article <4623@freja.diku.dk> dat0@rimfaxe.diku.dk (Dat-0 undervisningsassistent) writes: >>schwartz@shire.cs.psu.edu (Scott Schwartz) writes: >>>Alastair Milne writes: >>>| > while (input^ in [space, tab, newline, cr, formfeed]) do >>>| > get (input) >>>| >>>| How does this constitute not commiting to read the file variable? You are >>>| doing exactly that when you dereference the file variable to get its >>>| window. > >Here's a good example of how convenient the file buffer variable is: > >Suppose you want to allow the user to input a bunch of integers, separated >by any sequence of non-numeric characters. For example, the following >atrocity is legal input: > >,,100 ,20, >, > > 30 >40,, 5050 >,,, > >The program should process the integers 100, 20, 30, 40, and 5050. >Here is a trivial piece of Standard Pascal that does the job correctly. > >while not eof do begin > if (input^ >= '0') and (input^ <= '9') then begin > read(number); > process(number); > end > else > get(input); >end > >I admit that for most programming languages it is possible to come up >with simple and elegant solutions to selected bizarre problems. Too >bad there isn't one language that is universally applicable. I've been of the school that Pascal is ugly in this sense: it seems that the language is lacking because you don't say what you want to do. Here is the same code in C, more or less #include #include main() { int c = 0; int val; while (1) { while (!isdigit(c = getchar())) if (c == EOF) return 0; ungetc(c, stdin); /* read one too many character */ scanf("%d", &val); printf("%d\n", val); } } In C, we can't surreptitiously read a character (Pascal: input^). We have to really and truly read it using getchar(). Once we discover that we've read one too many characters, we "push it back" into the input stream: ungetc(c, stdin). Of course, the input stream must be buffered. The advantage of C's method is that we don't get obscure behavior: if we want to read a character, we read it (with getchar). If we want to "unread" it, we call ungetc. Larry Miller lmiller@venera.isi.edu (no uucp) USC/ISI 213-822-1511 4676 Admiralty Way Marina del Rey, CA. 90292