Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!watmath!clyde!burl!ulysses!allegra!mit-eddie!think!harvard!seismo!brl-adm!brl-smoke!smoke!rbj@icst-cmr From: rbj@icst-cmr (Root Boy Jim) Newsgroups: net.lang.c Subject: Re: mixing scanf and gets Message-ID: <2476@brl-smoke.ARPA> Date: Tue, 8-Apr-86 19:11:25 EST Article-I.D.: brl-smok.2476 Posted: Tue Apr 8 19:11:25 1986 Date-Received: Thu, 10-Apr-86 08:29:23 EST Sender: news@brl-smoke.ARPA Lines: 50 yoda@ittatc.ATC.ITT.UUCP (Todd C. Williams [Jedi Knight]) writes: >Is it possible to use gets() after scanf() ? >Is it a good idea to try to use gets() after scanf() ? >It doesn't work, so I tried adding "fflush(stdin);" >just before the gets(), but that doesn't help either. >If I do 2 "gets(str)"'s in a row, the second one works. > >Apparently, the scanf() is reading UP TO the newline, but >leaving that newline in the buffer; the gets() sees the >newline and thinks it is finished. So what's the problem? Use gets after scanf to eat the \n. Doug Gwyn replys: scanf() does whatever you tell it to with the input stream then stops. If you make it eat newlines, it will. There should be no problem mixing any of the STDIO input methods. However, it sounds to me like your application would be programmed better with the following scheme: while get-a-line-using-fgets parse-line-with-sscanf The way I understand it, scanf will eat input only as far as makes sense, ungetc'ing the rest. The problem with sscanf is that if your input only partially matches, there is no way to tell where `the rest' begins. Or am I in outer space? By the way, don't use gets(); your input buffer can be overrun if an input line is very long, resulting in unpredictable malfunctioning of your application. When Agreed. Gets is `obseleted' by fgets. you use fgets(), it is often wise to test the last character in the record and if it is a newline, replace it with a 0 string terminator before parsing the record. Which brings me to another point. Fgets is worthless on binary data. It returns its first argument, which I already know. If a null is part of the data, how do you know where it stopped reading. Well if you're lucky, there will be a newline in there and that's the end of it. But if you're reading blocks of nulls, you're SOL. I would like fgets to return the number of chars read. (Root Boy) Jim Cottrell Baseball in D.C. in `87!