Path: csiph.com!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: Shortened form of condition Date: Tue, 10 Nov 2015 09:29:23 -0800 Organization: None to speak of Lines: 60 Message-ID: References: <62775b24-22c8-4b78-85ca-6ca99456f2c5@googlegroups.com> <3093d138-02fd-4830-82b5-97feec5148e9@googlegroups.com> <87k2pqm7jw.fsf@bsb.me.uk> <7557bd69-d93f-4197-a72a-48f71f7614dd@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx02.eternal-september.org; posting-host="945944de09706c9b4e29b53c9d2efdc2"; logging-data="8874"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/zpi6ZuHMv7vyWo+DP9DFT" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:D/eGweAsFYvLvenYIQpkHT5I1ww= sha1:1Kk47mRzS6oDcLqv2e/Is6x7smA= Xref: csiph.com comp.lang.c:75635 Alla _ writes: > > > Here is the read_line() function: > void read_line (char buffer []) > { > char character; > int i = 0; > > do > { > character = getchar(); > buffer[i] = character; > i++; > } > while (character != '\n'); > > buffer[i - 1] = '\0'; > } > > It terminates when the '\n' is entered. And that function was provided for you as part of the course? I'm not going to judge the competence of your teacher(s) based on one function, but that's horrid. It's actually worse than gets(), which was so inherently unsafe it was removed from the language. (If you wrote it yourself, please consider my criticism to be toned down by a couple of order of magnitude.) If the user types more input than will fit into the buffer, it just keeps storing characters past the end of the buffer. And unlike gets(), it doesn't handle end-of-file or error conditions at all; it just assumes they'll never happen. If I type Ctrl-D on a Unix-like system, or Ctrl-Z on Windows, it goes into an infinite loop. I suggest using fgets(), checking the value it returns (which tells you if you've reached end-of-file) and dealing with the '\n' that it leaves at the end if the buffer yourself. char line[81]; if (fgets(line, sizeof line, stdin) == NULL) { /* end-of-file or error; call feof(stdin) or ferror(stdin) to find out which */ } else { const size_t len = strlen(line); if (line[len-1] == '\n') { line[len-1] = '\0'; } } If the input line is longer than 80 characters, the remainder of the line will be left for reading by the next call. -- Keith Thompson (The_Other_Keith) kst-u@mib.org Working, but not speaking, for JetHead Development, Inc. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister"