Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c > #76641 > unrolled thread

While or if: function to get next operator or operand

Started byAlla _ <modelling.data@gmail.com>
First post2015-11-20 08:06 -0800
Last post2015-11-20 20:43 -0800
Articles 20 on this page of 68 — 18 participants

Back to article view | Back to comp.lang.c


Contents

  While or if: function to get next operator or operand Alla _ <modelling.data@gmail.com> - 2015-11-20 08:06 -0800
    Re: While or if: function to get next operator or operand Malcolm McLean <malcolm.mclean5@btinternet.com> - 2015-11-20 08:17 -0800
      Re: While or if: function to get next operator or operand Richard Heathfield <rjh@cpax.org.uk> - 2015-11-20 16:44 +0000
    Re: While or if: function to get next operator or operand Eric Sosman <esosman@comcast-dot-net.invalid> - 2015-11-20 11:23 -0500
      Re: While or if: function to get next operator or operand Alla _ <modelling.data@gmail.com> - 2015-11-20 08:39 -0800
        Re: While or if: function to get next operator or operand Richard Heathfield <rjh@cpax.org.uk> - 2015-11-20 16:47 +0000
        Re: While or if: function to get next operator or operand Eric Sosman <esosman@comcast-dot-net.invalid> - 2015-11-20 11:54 -0500
          Re: While or if: function to get next operator or operand Alla _ <modelling.data@gmail.com> - 2015-11-20 09:13 -0800
          Re: While or if: function to get next operator or operand David Thompson <dave.thompson2@verizon.net> - 2015-12-06 08:04 -0500
        Re: While or if: function to get next operator or operand James Kuyper <jameskuyper@verizon.net> - 2015-11-20 12:02 -0500
    Re: While or if: function to get next operator or operand Richard Heathfield <rjh@cpax.org.uk> - 2015-11-20 16:41 +0000
      Re: While or if: function to get next operator or operand Alla _ <modelling.data@gmail.com> - 2015-11-20 09:11 -0800
        Re: While or if: function to get next operator or operand Richard Heathfield <rjh@cpax.org.uk> - 2015-11-20 17:39 +0000
          Re: While or if: function to get next operator or operand Alla _ <modelling.data@gmail.com> - 2015-11-20 10:42 -0800
          Re: While or if: function to get next operator or operand Lew Pitcher <lew.pitcher@digitalfreehold.ca> - 2015-11-21 14:58 -0500
            Re: While or if: function to get next operator or operand Richard Heathfield <rjh@cpax.org.uk> - 2015-11-23 12:21 +0000
          Re: While or if: function to get next operator or operand Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-11-21 21:29 +0000
            Re: While or if: function to get next operator or operand BartC <bc@freeuk.com> - 2015-11-21 22:31 +0000
              Re: While or if: function to get next operator or operand BartC <bc@freeuk.com> - 2015-11-22 10:57 +0000
                Re: While or if: function to get next operator or operand Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-11-22 13:45 +0000
            Re: While or if: function to get next operator or operand Lew Pitcher <lew.pitcher@digitalfreehold.ca> - 2015-11-22 01:31 -0500
            Re: While or if: function to get next operator or operand Tim Rentsch <txr@alumni.caltech.edu> - 2015-11-23 04:33 -0800
              Re: While or if: function to get next operator or operand Philip Lantz <prl@canterey.us> - 2015-11-23 23:44 -0800
          Re: While or if: function to get next operator or operand Rosario19 <Ros@invalid.invalid> - 2015-11-22 09:39 +0100
            Re: While or if: function to get next operator or operand Rosario19 <Ros@invalid.invalid> - 2015-11-22 09:49 +0100
              Re: While or if: function to get next operator or operand asetofsymbols@gmail.com - 2015-11-22 02:27 -0800
                Re: While or if: function to get next operator or operand asetofsymbols@gmail.com - 2015-11-22 02:32 -0800
          Re: While or if: function to get next operator or operand Lew Pitcher <lew.pitcher@digitalfreehold.ca> - 2015-11-22 10:02 -0500
            Re: While or if: function to get next operator or operand Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-11-23 17:23 +0000
              Re: While or if: function to get next operator or operand Lew Pitcher <lew.pitcher@digitalfreehold.ca> - 2015-11-23 12:31 -0500
                Re: While or if: function to get next operator or operand Lew Pitcher <lew.pitcher@digitalfreehold.ca> - 2015-11-23 13:02 -0500
          Re: While or if: function to get next operator or operand Alla _ <modelling.data@gmail.com> - 2015-11-22 07:06 -0800
            Re: While or if: function to get next operator or operand Barry Schwarz <schwarzb@dqel.com> - 2015-11-22 11:43 -0800
              Re: While or if: function to get next operator or operand Alla _ <modelling.data@gmail.com> - 2015-11-24 02:03 -0800
              Re: While or if: function to get next operator or operand Alla _ <modelling.data@gmail.com> - 2015-11-24 02:11 -0800
                Re: While or if: function to get next operator or operand James Kuyper <jameskuyper@verizon.net> - 2015-11-24 07:09 -0500
            Re: While or if: function to get next operator or operand Richard Heathfield <rjh@cpax.org.uk> - 2015-11-23 12:26 +0000
              Re: While or if: function to get next operator or operand raltbos@xs4all.nl (Richard Bos) - 2015-11-23 13:26 +0000
          Re: While or if: function to get next operator or operand Alla _ <modelling.data@gmail.com> - 2015-11-22 07:17 -0800
    Re: While or if: function to get next operator or operand James Kuyper <jameskuyper@verizon.net> - 2015-11-20 12:15 -0500
      Re: While or if: function to get next operator or operand Alla _ <modelling.data@gmail.com> - 2015-11-20 10:44 -0800
      Re: While or if: function to get next operator or operand Tim Rentsch <txr@alumni.caltech.edu> - 2015-11-20 12:31 -0800
        Re: While or if: function to get next operator or operand Lew Pitcher <lew.pitcher@digitalfreehold.ca> - 2015-11-20 15:38 -0500
          Re: While or if: function to get next operator or operand James Kuyper <jameskuyper@verizon.net> - 2015-11-20 16:14 -0500
            Re: While or if: function to get next operator or operand Lew Pitcher <lew.pitcher@digitalfreehold.ca> - 2015-11-20 16:55 -0500
              Re: While or if: function to get next operator or operand Geoff <geoff@invalid.invalid> - 2015-11-20 15:04 -0800
          Re: While or if: function to get next operator or operand Barry Schwarz <schwarzb@dqel.com> - 2015-11-20 20:59 -0800
          Re: While or if: function to get next operator or operand Alla _ <modelling.data@gmail.com> - 2015-11-20 23:50 -0800
            Re: While or if: function to get next operator or operand Alla _ <modelling.data@gmail.com> - 2015-11-21 00:18 -0800
          Re: While or if: function to get next operator or operand Tim Rentsch <txr@alumni.caltech.edu> - 2015-11-22 14:10 -0800
        Re: While or if: function to get next operator or operand Philip Lantz <prl@canterey.us> - 2015-11-22 19:00 -0800
          Re: While or if: function to get next operator or operand James Kuyper <jameskuyper@verizon.net> - 2015-11-23 06:57 -0500
            Re: While or if: function to get next operator or operand Philip Lantz <prl@canterey.us> - 2015-11-23 23:49 -0800
              Re: While or if: function to get next operator or operand James Kuyper <jameskuyper@verizon.net> - 2015-11-24 07:13 -0500
          Re: While or if: function to get next operator or operand Tim Rentsch <txr@alumni.caltech.edu> - 2015-11-23 07:55 -0800
            Re: While or if: function to get next operator or operand Philip Lantz <prl@canterey.us> - 2015-11-23 23:36 -0800
              Re: While or if: function to get next operator or operand Tim Rentsch <txr@alumni.caltech.edu> - 2015-11-27 13:32 -0800
      Re: While or if: function to get next operator or operand Eric Sosman <esosman@comcast-dot-net.invalid> - 2015-11-20 16:13 -0500
        Re: While or if: function to get next operator or operand Tim Rentsch <txr@alumni.caltech.edu> - 2015-11-22 13:54 -0800
    Re: While or if: function to get next operator or operand Geoff <geoff@invalid.invalid> - 2015-11-20 12:19 -0800
    Re: While or if: function to get next operator or operand Tim Rentsch <txr@alumni.caltech.edu> - 2015-11-20 15:32 -0800
      Re: While or if: function to get next operator or operand Chad <cdalten@gmail.com> - 2015-11-20 18:38 -0800
        Re: While or if: function to get next operator or operand Keith Thompson <kst-u@mib.org> - 2015-11-20 19:45 -0800
          Re: While or if: function to get next operator or operand Malcolm McLean <malcolm.mclean5@btinternet.com> - 2015-11-20 20:12 -0800
        Re: While or if: function to get next operator or operand Alla _ <modelling.data@gmail.com> - 2015-11-20 20:45 -0800
          Re: While or if: function to get next operator or operand Malcolm McLean <malcolm.mclean5@btinternet.com> - 2015-11-20 21:04 -0800
        Re: While or if: function to get next operator or operand Tim Rentsch <txr@alumni.caltech.edu> - 2015-11-22 13:57 -0800
      Re: While or if: function to get next operator or operand Alla _ <modelling.data@gmail.com> - 2015-11-20 20:43 -0800

Page 2 of 4 — ← Prev page 1 [2] 3 4  Next page →


#76836

FromLew Pitcher <lew.pitcher@digitalfreehold.ca>
Date2015-11-22 01:31 -0500
Message-ID<1jd4y.82529$WF.67998@fx30.iad>
In reply to#76804
On Saturday November 21 2015 16:29, in comp.lang.c, "Ben Bacarisse"
<ben.usenet@bsb.me.uk> wrote:

> Richard Heathfield <rjh@cpax.org.uk> writes:
> <snip>
>> Here's the challenge:
>>
>> Write a correct C program that reads standard input and reproduces it
>> on standard output verbatim *except that* each word (which I define as
>> a contiguous series of letters terminated on each end by a non-letter
>> or by one end or other of the input) is displayed with the inner
>> letters (i.e. not the first and last letters) sorted into alphabetical
>> order. The first and last letters should stay in their correct
>> positions. I will now demonstrate what I mean, using this paragraph as
>> input.
> 
> That looked like it was worth a try, so here's a version that (to all
> intents and purposes) does away with the arbitrary size limit and allows
> for an easy definition of word characters and their collating sequence.
> It's terse to the point of obfuscation but then it was just for fun...

Very nice, and elegant.


-- 
Lew Pitcher
"In Skills, We Trust"
PGP public key available upon request

[toc] | [prev] | [next] | [standalone]


#76986

FromTim Rentsch <txr@alumni.caltech.edu>
Date2015-11-23 04:33 -0800
Message-ID<kfnpoz0520b.fsf@x-alumni2.alumni.caltech.edu>
In reply to#76804
Ben Bacarisse <ben.usenet@bsb.me.uk> writes:

> Richard Heathfield <rjh@cpax.org.uk> writes:
> <snip>
>> Here's the challenge:
>>
>> Write a correct C program that reads standard input and reproduces
>> it on standard output verbatim *except that* each word (which I
>> define as a contiguous series of letters terminated on each end by
>> a non-letter or by one end or other of the input) is displayed with
>> the inner letters (i.e. not the first and last letters) sorted into
>> alphabetical order.  The first and last letters should stay in
>> their correct positions.  I will now demonstrate what I mean, using
>> this paragraph as input.
>
> That looked like it was worth a try, so here's a version that (to
> all intents and purposes) does away with the arbitrary size limit
> and allows for an easy definition of word characters and their
> collating sequence.  It's terse to the point of obfuscation but then
> it was just for fun...  [..code snipped..]

Clever.  A tip of the hat to you sir.

After I figured out how you were doing the letter outputs, but
before looking at the details, I thought I would try writing
something myself.  To make it more interesting I decided to make
the program as sparse as I could.  Here is the result with just a
few pieces left out:

    #include ...
    #include ...

    static char ...;

    int
    main(){
        static int ...;

        return  ...;
    }

That's the whole program, not counting what's in the ...'s.  If this
looks interesting have a go at writing something using this outline;
I think anyone who does will find it worth the effort.

[toc] | [prev] | [next] | [standalone]


#77059

FromPhilip Lantz <prl@canterey.us>
Date2015-11-23 23:44 -0800
Message-ID<MPG.30bdb546504b3514a8@news.eternal-september.org>
In reply to#76986
Tim Rentsch wrote:
> Ben Bacarisse writes:
> > Richard Heathfield writes:
> >> Here's the challenge:
> >>
> >> Write a correct C program that reads standard input and reproduces
> >> it on standard output verbatim *except that* each word (which I
> >> define as a contiguous series of letters terminated on each end by
> >> a non-letter or by one end or other of the input) is displayed with
> >> the inner letters (i.e. not the first and last letters) sorted into
> >> alphabetical order.  The first and last letters should stay in
> >> their correct positions.  I will now demonstrate what I mean, using
> >> this paragraph as input.
> >
> > That looked like it was worth a try, so here's a version that (to
> > all intents and purposes) does away with the arbitrary size limit
> > and allows for an easy definition of word characters and their
> > collating sequence.  It's terse to the point of obfuscation but then
> > it was just for fun...  [..code snipped..]
> 
> Clever.  A tip of the hat to you sir.
> 
> After I figured out how you were doing the letter outputs, but
> before looking at the details, I thought I would try writing
> something myself.  To make it more interesting I decided to make
> the program as sparse as I could.  Here is the result with just a
> few pieces left out:
> 
>     #include ...
>     #include ...
> 
>     static char ...;
> 
>     int
>     main(){
>         static int ...;
> 
>         return  ...;
>     }
> 
> That's the whole program, not counting what's in the ...'s.  If this
> looks interesting have a go at writing something using this outline;
> I think anyone who does will find it worth the effort.

Nice.

[toc] | [prev] | [next] | [standalone]


#76843

FromRosario19 <Ros@invalid.invalid>
Date2015-11-22 09:39 +0100
Message-ID<ifv25btei1g4tth1jmtqt1dv7hgvc0u9dh@4ax.com>
In reply to#76655
On Fri, 20 Nov 2015 17:39:41 +0000, Richard Heathfield wrote:
>On 20/11/15 17:11, Alla _ wrote:
>
><snip>
>
>> I have not skipped through pages. The only thing I have been doing
>> during the last three days is reading and studying K&R.
>
>I was a touch harsh, for which I apologise. But you are still going way 
>too fast. You are trying to absorb new material without having a firm 
>foundation in what has gone before.
>
>To demonstrate this, I would like to offer you a little challenge if I 
>may. (No doubt other people will also chip in their own answers, but I 
>would urge you to ignore those answers until you have come up with your 
>own solution.)
>
>Here's the challenge:
>
>Write a correct C program that reads standard input and reproduces it on 
>standard output verbatim *except that* each word (which I define as a 
>contiguous series of letters terminated on each end by a non-letter or 
>by one end or other of the input) is displayed with the inner letters 
>(i.e. not the first and last letters) sorted into alphabetical order. 
>The first and last letters should stay in their correct positions. I 
>will now demonstrate what I mean, using this paragraph as input.
>
>Wirte a cceorrt C pagorrm taht rades saadnrtd input and rcdeeoprus it on 
>saadnrtd optuut vabeirtm *ecepxt taht* each word (wchih I define as a 
>cginootuus seeirs of leettrs taeeimnrtd on each end by a non-leettr or 
>by one end or oehtr of the input) is daeilpsyd with the iennr leettrs 
>(i.e. not the first and last leertts) seortd into aaabcehilptl oderr. 
>The first and last leertts shloud saty in tehir cceorrt piinoosts. I 
>will now daemnorstte waht I maen, uinsg this paaagprrh as input.
>
>You may assume that no word exceeds 64 letters in length.
>
>If you have absorbed everything you have read in K&R up to page 77, this 
>will be a very easy exercise, and you will not need any help with it.
>
>So if you struggle with it (and I think you will), that is a sign that 
>you are going too fast.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define  u32   unsigned
#define  i32   int
#define  u8    unsigned char

#define  R  return
#define  P  printf
#define  F  for
#define  GG(a,b) if(a)goto b
#define  G  goto

i32 WrdLetter(i32  a){R  isalpha(a);}

i32  cmp(const void*  a, const void* b)
{u8  *aa=(u8*)a, *bb=(u8*)b; R ((i32)*aa)-*bb;}

// Programma che legge le parole da input secondo la 
// di sopra definizione di lettere di una parola
// e le scrive sull'output conservando la lettera iniziale
// e finale ma ordinando in maniera crescente tutte le 
// altre in mezzo.
int  main(void)
{u8            *buf;
 u32  w=1000,j,iWrd;
 i32        k, r, v;

 buf=(u8*) malloc(w+8);
 if(buf==0){P("Memory insufficient\n");
l1:         free(buf);
            R  1;   // wrong 
           }
 F(iWrd=0; ; )
   {k=getchar();
    if(k==EOF||!(v=WrdLetter(k))) // EOF or ERROR or not alpha
      {if(iWrd){// len=iWrd=4  0123  buf+1->1  lenCmp=2=4-2=iWrd-2
svuotaBuf:      // ordina il buffer della parola 
                if(iWrd>3) qsort(buf+1, iWrd-2, 1, cmp);

                //Svuota buffer word;
                F(j=0; j<iWrd; ++j)
                   {r=putchar(buf[j]);
                    GG(r==EOF, l1);
                   }
                iWrd=0;
               }
      }
    GG(k==EOF,l3); // exit ok
    if(v){// scrivi nel buffer
          GG(iWrd>=w, l1);
          buf[iWrd++]=(u8)k;
         }
    else {// scrivi nel output
          r=putchar(k);
          GG(r==EOF, l1);
         }
   }
l3:
 GG( ferror(stdin)||ferror(stdout), l1);
 free(buf);
 R   0; //ok
}

[toc] | [prev] | [next] | [standalone]


#76844

FromRosario19 <Ros@invalid.invalid>
Date2015-11-22 09:49 +0100
Message-ID<hb035b13eujcfpkfglj0eakk3vg5ch74d1@4ax.com>
In reply to#76843
On Sun, 22 Nov 2015 09:39:53 +0100, Rosario19 wrote:

>i32  cmp(const void*  a, const void* b)
>{u8  *aa=(u8*)a, *bb=(u8*)b; R ((i32)*aa)-*bb;}

the right function should be instead
i32  cmp(const void*  a, const void* b)
{u8  *aa=(u8*)a, *bb=(u8*)b; R tolower(*aa)-tolower(*bb);}

[toc] | [prev] | [next] | [standalone]


#76846

Fromasetofsymbols@gmail.com
Date2015-11-22 02:27 -0800
Message-ID<85a762e7-01cc-431f-961b-96ff02b3c381@googlegroups.com>
In reply to#76844
i32  cmp(const void*  a, const void* b) 

{u8  *aa=(u8*)a, *bb=(u8*)b;
 i32  ai, bi, ar, br;
 ai=*aa; bi=*bb;
 if(!isupper(ai)==!isupper(bi))//entrambe maiuscole...
           R  ai-bi;
 ar=tolower(*aa); br=tolower(*bb);
 if(ai==bi) R isupper(ai)? 1:-1;
 R ar-br;
}

[toc] | [prev] | [next] | [standalone]


#76848

Fromasetofsymbols@gmail.com
Date2015-11-22 02:32 -0800
Message-ID<13656651-401e-4adc-946b-c0226130aed5@googlegroups.com>
In reply to#76846
i32  cmp(const void*  a, const void* b) 
{u8  *aa=(u8*)a, *bb=(u8*)b; 

 i32  ai, bi, ar, br; 
 ai=*aa; bi=*bb; 
 if(!isupper(ai)==!isupper(bi))//entrambe maiuscole... 
           R  ai-bi; 
 ar=tolower(*aa); br=tolower(*bb); 
 if(ar==br) R isupper(ai)? 1:-1; 
 R ar-br; 
}

[toc] | [prev] | [next] | [standalone]


#76865

FromLew Pitcher <lew.pitcher@digitalfreehold.ca>
Date2015-11-22 10:02 -0500
Message-ID<kOk4y.221343$rR1.152847@fx19.iad>
In reply to#76655
On Friday November 20 2015 12:39, in comp.lang.c, "Richard Heathfield"
<rjh@cpax.org.uk> wrote:
[snip]

> Here's the challenge:
> 
> Write a correct C program that reads standard input and reproduces it on
> standard output verbatim *except that* each word (which I define as a
> contiguous series of letters terminated on each end by a non-letter or
> by one end or other of the input) is displayed with the inner letters
> (i.e. not the first and last letters) sorted into alphabetical order.
> The first and last letters should stay in their correct positions. I
> will now demonstrate what I mean, using this paragraph as input.
> 
> Wirte a cceorrt C pagorrm taht rades saadnrtd input and rcdeeoprus it on
> saadnrtd optuut vabeirtm *ecepxt taht* each word (wchih I define as a
> cginootuus seeirs of leettrs taeeimnrtd on each end by a non-leettr or
> by one end or oehtr of the input) is daeilpsyd with the iennr leettrs
> (i.e. not the first and last leertts) seortd into aaabcehilptl oderr.
> The first and last leertts shloud saty in tehir cceorrt piinoosts. I
> will now daemnorstte waht I maen, uinsg this paaagprrh as input.
> 
> You may assume that no word exceeds 64 letters in length.
> 
> If you have absorbed everything you have read in K&R up to page 77, this
> will be a very easy exercise, and you will not need any help with it.

[snip]

/* challenge.c
**
** cc -o challenge -Wall -ansi -pedantic -std=c99 challenge.c
**
** Uses local, custom code to determine alphabetics and to sort,
** as K&R does not introduce isalpha() or qsort() before page 77.
*/

#include <stdio.h>

int IsAlphabetic(int);
void sortBytes(unsigned char [], size_t);

int main(void)
{
  int byte;
  unsigned char word[65] = {0};
  size_t byteposn = 0;

  while ((byte = getchar()) != EOF)
  {
    if (IsAlphabetic(byte))
      word[byteposn++] = byte;
    else
    {
      if (byteposn > 0)
      {
        if (byteposn > 3)
          sortBytes(word+1,byteposn-2);
        printf("%s",word);
      }
      putchar(byte);
      byteposn = 0;
    }
    word[byteposn] = 0;
  } 

  return 0;
}

/*
** Use custom code to determine if a value is alphabetic
*/
int IsAlphabetic(int byte)
{
  unsigned char alphabet[]
                = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  unsigned char *ptr;

  for (ptr = alphabet; *ptr && *ptr != byte; ++ptr)
  { /*nop*/ }

  return *ptr != 0;
}

/*
** Use custom code to sort characters into ascending sequence
** (shell sort, per K&R "The C Programming Language")
*/
void sortBytes(unsigned char array[], size_t count)
{
  size_t gap;

  for (gap = count/2; gap > 0; gap /= 2)
  {
    size_t i;

    for (i = gap; i < count; ++i)
    {
      int j;

      for (j = i-gap; j >= 0 && array[j] > array[j+gap]; j -= gap)
      {
        unsigned char temp;

        temp         = array[j];
        array[j]     = array[j+gap];
        array[j+gap] = temp; 
      }
    }
  }
}

-- 
Lew Pitcher
"In Skills, We Trust"
PGP public key available upon request

[toc] | [prev] | [next] | [standalone]


#77013

FromBen Bacarisse <ben.usenet@bsb.me.uk>
Date2015-11-23 17:23 +0000
Message-ID<87egfgk4td.fsf@bsb.me.uk>
In reply to#76865
Lew Pitcher <lew.pitcher@digitalfreehold.ca> writes:

> On Friday November 20 2015 12:39, in comp.lang.c, "Richard Heathfield"
> <rjh@cpax.org.uk> wrote:
> [snip]
>
>> Here's the challenge:
>> 
>> Write a correct C program that reads standard input and reproduces it on
>> standard output verbatim *except that* each word (which I define as a
>> contiguous series of letters terminated on each end by a non-letter or
>> by one end or other of the input) is displayed with the inner letters
>> (i.e. not the first and last letters) sorted into alphabetical order.
>> The first and last letters should stay in their correct positions. I
>> will now demonstrate what I mean, using this paragraph as input.
<snip>
>> You may assume that no word exceeds 64 letters in length.
<snip>
> /* challenge.c
> **
> ** cc -o challenge -Wall -ansi -pedantic -std=c99 challenge.c
> **
> ** Uses local, custom code to determine alphabetics and to sort,
> ** as K&R does not introduce isalpha() or qsort() before page 77.
> */
>
> #include <stdio.h>
>
> int IsAlphabetic(int);
> void sortBytes(unsigned char [], size_t);
>
> int main(void)
> {
>   int byte;
>   unsigned char word[65] = {0};
>   size_t byteposn = 0;
>
>   while ((byte = getchar()) != EOF)
>   {
>     if (IsAlphabetic(byte))
>       word[byteposn++] = byte;
>     else
>     {
>       if (byteposn > 0)
>       {
>         if (byteposn > 3)
>           sortBytes(word+1,byteposn-2);
>         printf("%s",word);
>       }
>       putchar(byte);
>       byteposn = 0;
>     }
>     word[byteposn] = 0;
>   } 
>
>   return 0;
> }

I hope you won't mind a niggle...  If the last word is not followed by a
non-alphabetic character, it is not printed.  I think you can argue here
that a text file should have a terminating newline, but I prefer to
handle such cases nonetheless.

<snip>
-- 
Ben.

[toc] | [prev] | [next] | [standalone]


#77014

FromLew Pitcher <lew.pitcher@digitalfreehold.ca>
Date2015-11-23 12:31 -0500
Message-ID<O3I4y.102737$2K.97903@fx09.iad>
In reply to#77013
On Monday November 23 2015 12:23, in comp.lang.c, "Ben Bacarisse"
<ben.usenet@bsb.me.uk> wrote:

> Lew Pitcher <lew.pitcher@digitalfreehold.ca> writes:
> 
>> On Friday November 20 2015 12:39, in comp.lang.c, "Richard Heathfield"
>> <rjh@cpax.org.uk> wrote:
>> [snip]
>>
>>> Here's the challenge:
>>> 
>>> Write a correct C program that reads standard input and reproduces it on
>>> standard output verbatim *except that* each word (which I define as a
>>> contiguous series of letters terminated on each end by a non-letter or
>>> by one end or other of the input) is displayed with the inner letters
>>> (i.e. not the first and last letters) sorted into alphabetical order.
>>> The first and last letters should stay in their correct positions. I
>>> will now demonstrate what I mean, using this paragraph as input.
> <snip>
>>> You may assume that no word exceeds 64 letters in length.
> <snip>
>> /* challenge.c
>> **
>> ** cc -o challenge -Wall -ansi -pedantic -std=c99 challenge.c
>> **
>> ** Uses local, custom code to determine alphabetics and to sort,
>> ** as K&R does not introduce isalpha() or qsort() before page 77.
>> */
>>
>> #include <stdio.h>
>>
>> int IsAlphabetic(int);
>> void sortBytes(unsigned char [], size_t);
>>
>> int main(void)
>> {
>>   int byte;
>>   unsigned char word[65] = {0};
>>   size_t byteposn = 0;
>>
>>   while ((byte = getchar()) != EOF)
>>   {
>>     if (IsAlphabetic(byte))
>>       word[byteposn++] = byte;
>>     else
>>     {
>>       if (byteposn > 0)
>>       {
>>         if (byteposn > 3)
>>           sortBytes(word+1,byteposn-2);
>>         printf("%s",word);
>>       }
>>       putchar(byte);
>>       byteposn = 0;
>>     }
>>     word[byteposn] = 0;
>>   }
>>
>>   return 0;
>> }
> 
> I hope you won't mind a niggle...  

Not at all.

> If the last word is not followed by a 
> non-alphabetic character, it is not printed.  I think you can argue here
> that a text file should have a terminating newline, but I prefer to
> handle such cases nonetheless.

Good catch. I'll have to look into that.

-- 
Lew Pitcher
"In Skills, We Trust"
PGP public key available upon request

[toc] | [prev] | [next] | [standalone]


#77018

FromLew Pitcher <lew.pitcher@digitalfreehold.ca>
Date2015-11-23 13:02 -0500
Message-ID<wwI4y.178663$M%.78235@fx20.iad>
In reply to#77014
On Monday November 23 2015 12:31, in comp.lang.c, "Lew Pitcher"
<lew.pitcher@digitalfreehold.ca> wrote:

> On Monday November 23 2015 12:23, in comp.lang.c, "Ben Bacarisse"
> <ben.usenet@bsb.me.uk> wrote:
> 
>> Lew Pitcher <lew.pitcher@digitalfreehold.ca> writes:
>> 
>>> On Friday November 20 2015 12:39, in comp.lang.c, "Richard Heathfield"
>>> <rjh@cpax.org.uk> wrote:
>>> [snip]
>>>
>>>> Here's the challenge:
>>>> 
>>>> Write a correct C program that reads standard input and reproduces it on
>>>> standard output verbatim *except that* each word (which I define as a
>>>> contiguous series of letters terminated on each end by a non-letter or
>>>> by one end or other of the input) is displayed with the inner letters
>>>> (i.e. not the first and last letters) sorted into alphabetical order.
>>>> The first and last letters should stay in their correct positions. I
>>>> will now demonstrate what I mean, using this paragraph as input.
>> <snip>
>>>> You may assume that no word exceeds 64 letters in length.
>> <snip>
>>> /* challenge.c
>>> **
>>> ** cc -o challenge -Wall -ansi -pedantic -std=c99 challenge.c
>>> **
>>> ** Uses local, custom code to determine alphabetics and to sort,
>>> ** as K&R does not introduce isalpha() or qsort() before page 77.
>>> */
>>>
>>> #include <stdio.h>
>>>
>>> int IsAlphabetic(int);
>>> void sortBytes(unsigned char [], size_t);
>>>
>>> int main(void)
>>> {
>>>   int byte;
>>>   unsigned char word[65] = {0};
>>>   size_t byteposn = 0;
>>>
>>>   while ((byte = getchar()) != EOF)
>>>   {
>>>     if (IsAlphabetic(byte))
>>>       word[byteposn++] = byte;
>>>     else
>>>     {
>>>       if (byteposn > 0)
>>>       {
>>>         if (byteposn > 3)
>>>           sortBytes(word+1,byteposn-2);
>>>         printf("%s",word);
>>>       }
>>>       putchar(byte);
>>>       byteposn = 0;
>>>     }
>>>     word[byteposn] = 0;
>>>   }
>>>
>>>   return 0;
>>> }
>> 
>> I hope you won't mind a niggle...
> 
> Not at all.
> 
>> If the last word is not followed by a
>> non-alphabetic character, it is not printed.  I think you can argue here
>> that a text file should have a terminating newline, but I prefer to
>> handle such cases nonetheless.
> 
> Good catch. I'll have to look into that.

Here's a revised main(). The IsAlphabetic() and sortBytes() functions stand
unchanged.


/* challenge.c
**
** cc -o challenge -Wall -ansi -pedantic -std=c99 challenge.c
**
** Uses local, custom code to determine alphabetics and to sort,
** as K&R does not introduce isalpha() or qsort() before page 77.
*/

#include <stdio.h>

int IsAlphabetic(int);
void sortBytes(unsigned char [], size_t);

int main(void)
{
  int byte;
  unsigned char word[65] = {0};
  size_t byteposn = 0;

  do
  {
    if (IsAlphabetic(byte = getchar()))
      word[byteposn++] = byte;
    else
    {
      if (byteposn > 0)
      {
        if (byteposn > 3)
          sortBytes(word+1,byteposn-2);
        printf("%s",word);
      }
      byteposn = 0;
      if (byte != EOF) putchar(byte);
    }
    word[byteposn] = 0;
  }
  while (byte != EOF);

  return 0;
}

/*
** Use custom code to determine if a value is alphabetic
*/
int IsAlphabetic(int byte)
{
  unsigned char alphabet[]
                = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  unsigned char *ptr;

  for (ptr = alphabet; *ptr && *ptr != byte; ++ptr)
  { /*nop*/ }

  return *ptr != 0;
}

/*
** Use custom code to sort characters into ascending sequence
** (shell sort, per K&R "The C Programming Language")
*/
void sortBytes(unsigned char array[], size_t count)
{
  size_t gap;

  for (gap = count/2; gap > 0; gap /= 2)
  {
    size_t i;

    for (i = gap; i < count; ++i)
    {
      int j;

      for (j = i-gap; j >= 0 && array[j] > array[j+gap]; j -= gap)
      {
        unsigned char temp;

        temp         = array[j];
        array[j]     = array[j+gap];
        array[j+gap] = temp; 
      }
    }
  }
}


-- 
Lew Pitcher
"In Skills, We Trust"
PGP public key available upon request

[toc] | [prev] | [next] | [standalone]


#76866

FromAlla _ <modelling.data@gmail.com>
Date2015-11-22 07:06 -0800
Message-ID<22f32a21-9ea5-435d-a182-0a8a4dfb3a7a@googlegroups.com>
In reply to#76655
<snip>

Below is a program that represent only a partial implementation of a given task.

Not done:

1) although, the program can receive any text (with a slight change 
made to a condition for input text, i.e. putting back EOF), as showed in comments, but it sorts only one word;
and doesn't yet follow the condition of keeping the first and the last
letters unchanged;

2) have not managed to come up with reasonable function to discern a 
single word in a character string to apply a sort function to; although
I have a function that discerns only alphabetical characters from the input,
and assigns those to a new array, it doesn't separate words. Therefore, I am
not showing it here.

#include <stdio.h>
#include <ctype.h>
#include <string.h>

/* maximum length of the text */
#define MAX 1000

void get_text (char *text, int length);
void swap(char *letters, int *gap, int *j);
void sort(char *word);

int main (void)
{
    char input_text[MAX];
    
    printf("Please, enter one word; upper case letters are allowed\n");
    get_text (input_text, MAX);
    
    printf("%s\n", input_text);
    
    sort(input_text);
    
    printf("%s\n", input_text);
    
    return 0;
}

/* Function to get input text from the user */
void get_text (char *text, int length)
{
    int i, c;
    
    /* in original file (c = getchar()) != EOF;
     here, with != EOF condition, the sort function
     didn't turn back the upper case letter*/
    for (i = 0; i <= length - 1 && (c = getchar()) != '\n'; i++)
    {
        *(text + i) = c;
    }
    
    *(text + i) = '\0';
}

/* Function to swap letters if out of order */
void swap(char *letters, int *gap, int *j)
{
    int tmp = letters[*j];
    letters[*j] = letters[*j + *gap];
    letters[*j + *gap] = tmp;
}

/* Function to sort out-of-order letters */
void sort(char *word)
{
    int i, j, gap;
    int length = strlen(word);
    
    for (gap = length / 2; gap > 0; gap /= 2)
    {
        for (i = gap; i < length; i++)
        {
            for (j = i - gap; j >= 0; j -= gap)
            {
                if (!isupper(word[j]) && !isupper(word[j + gap]) && word[j] > word[j + gap])
                {
                    swap(word, &gap, &j);
                }
                
                else if (isupper(word[j + gap]))
                {
                    word[j + gap] = word[j + gap] - 'A' + 'a';
                    
                    if (isupper(word[j]))
                    {
                        word[j] = word[j] - 'A' + 'a';
                        
                        if (word[j] > word[j + gap])
                        {
                            swap(word, &gap, &j);
                        }
                        
                        word[j] = toupper(word[j]);
                    }
                    else if (word[j] > word[j + gap])
                    {
                        swap(word, &gap, &j);
                    }
                    word[j + gap] = toupper(word[j + gap]);
                }
                
                else if (isupper(word[j]))
                {
                    word[j] = word[j] - 'A' + 'a';
                    
                    if (isupper(word[j + gap]))
                    {
                        word[j + gap] = word[j + gap] - 'A' + 'a';
                        
                        if (word[j] > word[j + gap])
                        {
                            swap(word, &gap, &j);
                        }
                        
                        word[j + gap] = toupper(word[j + gap]);
                    }
                    else if (word[j] > word[j + gap])
                    {
                        swap(word, &gap, &j);
                    }
                    word[j] = toupper(word[j]);
                }
            }
        }
    }
}

[toc] | [prev] | [next] | [standalone]


#76904

FromBarry Schwarz <schwarzb@dqel.com>
Date2015-11-22 11:43 -0800
Message-ID<b6445bdoh79tif8e3ssnipha0t09dotedu@4ax.com>
In reply to#76866
On Sun, 22 Nov 2015 07:06:44 -0800 (PST), Alla _
<modelling.data@gmail.com> wrote:

<snip>

>#include <stdio.h>
>#include <ctype.h>
>#include <string.h>
>
>/* maximum length of the text */
>#define MAX 1000
>
>void get_text (char *text, int length);
>void swap(char *letters, int *gap, int *j);
>void sort(char *word);
>
>int main (void)
>{
>    char input_text[MAX];
>    
>    printf("Please, enter one word; upper case letters are allowed\n");
>    get_text (input_text, MAX);
>    
>    printf("%s\n", input_text);

It would be nice for users of your software if you told them what the
output represented.  Something like
     printf("Original text: %s\n", input_text);

>    sort(input_text);
>

It is not necessary to double space almost every line of your
programs.  The more you can see in a single screen the easier it is to
visualize the flow.  Reserve the double spacing to mark off
significant sections of a function.
    
>    printf("%s\n", input_text);
>    
>    return 0;
>}
>
>/* Function to get input text from the user */
>void get_text (char *text, int length)
>{
>    int i, c;
>    
>    /* in original file (c = getchar()) != EOF;
>     here, with != EOF condition, the sort function
>     didn't turn back the upper case letter*/
>    for (i = 0; i <= length - 1 && (c = getchar()) != '\n'; i++)
>    {
>        *(text + i) = c;

While obviously correct, the is seldom the common idiom for stepping
through an array.  It is more characters to type, harder to read, and
ponderously more complex when dealing with arrays of more than one
dimension.  What do have against
     text[i] = c;

>    }
>    
>    *(text + i) = '\0';
>}
>
>/* Function to swap letters if out of order */
>void swap(char *letters, int *gap, int *j)

Why would you elect to pass pointers to int when the only thing you is
access the actual int values themselves?  Isn't letters[j+gap]
significantly easier to read?

Passing a pointer suggests that either you intend to change the value
of the int pointed to or that you have an array of int and intend to
use more than one value from the array.

(Side note: passing a pointer to struct is often more efficient than
passing the struct itself but that is not an issue in this function.)

>{
>    int tmp = letters[*j];
>    letters[*j] = letters[*j + *gap];
>    letters[*j + *gap] = tmp;
>}
>
>/* Function to sort out-of-order letters */
>void sort(char *word)
>{
>    int i, j, gap;
>    int length = strlen(word);
>    
>    for (gap = length / 2; gap > 0; gap /= 2)
>    {
>        for (i = gap; i < length; i++)
>        {
>            for (j = i - gap; j >= 0; j -= gap)
>            {
>                if (!isupper(word[j]) && !isupper(word[j + gap]) && word[j] > word[j + gap])

Combining the test for two upper case characters with the test for
swapping causes unnecessary work.  If the j and j+gap characters are A
and B respectively, the if evaluates to false.
>                {
>                    swap(word, &gap, &j);
>                }
>                
>                else if (isupper(word[j + gap]))

This if evaluates to true.

>                {
>                    word[j + gap] = word[j + gap] - 'A' + 'a';

You convert the B to b.  Why did you not use tolower the way you use
toupper below?
                    
>                    if (isupper(word[j]))

This if evaluates to true.

>                    {
>                        word[j] = word[j] - 'A' + 'a';

You convert A to a.
                        
>                        if (word[j] > word[j + gap])

This if evaluates to false

>                        {
>                            swap(word, &gap, &j);
>                        }
>                        
>                        word[j] = toupper(word[j]);
>                    }
>                    else if (word[j] > word[j + gap])

This if is not evaluated.

>                    {
>                        swap(word, &gap, &j);
>                    }
>                    word[j + gap] = toupper(word[j + gap]);
>                }
>                
>                else if (isupper(word[j]))

You have a tremendous amount of duplicated code to deal with the four
case situations (both upper case, first upper case and second lower
case, etc).  Consider:
     Test each letter:
          If upper case set a flag and convert it to lower.
          Else reset the flag.
     Test for swap:
          If necessary swap the letters and the flags.
     Test each flag:
          If appropriate, convert corresponding letter back to upper.

On the other hand, do you even need to worry about case.  Did the
problem statement specify that B and b short sort together?  What
would be so terrible if B sorted before a (in ASCII) or if b sorted
before A (in EBCDIC)?

>                {
>                    word[j] = word[j] - 'A' + 'a';
>                    
>                    if (isupper(word[j + gap]))
>                    {
>                        word[j + gap] = word[j + gap] - 'A' + 'a';
>                        
>                        if (word[j] > word[j + gap])
>                        {
>                            swap(word, &gap, &j);
>                        }
>                        
>                        word[j + gap] = toupper(word[j + gap]);
>                    }
>                    else if (word[j] > word[j + gap])
>                    {
>                        swap(word, &gap, &j);
>                    }
>                    word[j] = toupper(word[j]);
>                }
>            }
>        }
>    }
>}

-- 
Remove del for email

[toc] | [prev] | [next] | [standalone]


#77069

FromAlla _ <modelling.data@gmail.com>
Date2015-11-24 02:03 -0800
Message-ID<d4e906d2-8204-4384-9858-8718db009fc1@googlegroups.com>
In reply to#76904
<snip>
> >    for (i = 0; i <= length - 1 && (c = getchar()) != '\n'; i++)
> >    {
> >        *(text + i) = c;
> 
> While obviously correct, the is seldom the common idiom for stepping
> through an array.  It is more characters to type, harder to read, and
> ponderously more complex when dealing with arrays of more than one
> dimension.  What do have against
>      text[i] = c;
> 
Yes. Honestly, I was testing my understanding of how to pass pointers 
to a function.
> >    }
> >    
> >    *(text + i) = '\0';
> >}
> >
> >/* Function to swap letters if out of order */
> >void swap(char *letters, int *gap, int *j)
> 
> Why would you elect to pass pointers to int when the only thing you is
> access the actual int values themselves?  Isn't letters[j+gap]
> significantly easier to read?
> 
> Passing a pointer suggests that either you intend to change the value
> of the int pointed to or that you have an array of int and intend to
> use more than one value from the array.
> 
> (Side note: passing a pointer to struct is often more efficient than
> passing the struct itself but that is not an issue in this function.)
> 
> >{
> >    int tmp = letters[*j];
> >    letters[*j] = letters[*j + *gap];
> >    letters[*j + *gap] = tmp;
> >}
> >
Same reason: testing myself. Indeed, these pointers to ints are not required
here, because they are not changing original values.


> >                if (!isupper(word[j]) && !isupper(word[j + gap]) && word[j] > word[j + gap])
> 
> Combining the test for two upper case characters with the test for
> swapping causes unnecessary work.  If the j and j+gap characters are A
> and B respectively, the if evaluates to false.
> >                {
> >                    swap(word, &gap, &j);
> >                }
> >                
I see. I should have written two if statements, putting the test for swapping
into the inner if statement:

if (!isupper(word[j]) && !isupper(word[j + gap]))
{
   if (word[j] > word[j + gap])
      swap(word, &gap, &j);
}
<snip>

[toc] | [prev] | [next] | [standalone]


#77071

FromAlla _ <modelling.data@gmail.com>
Date2015-11-24 02:11 -0800
Message-ID<72028fec-8b45-46c0-b033-13cd0e8137a3@googlegroups.com>
In reply to#76904
<snip>
> 
> >                {
> >                    word[j + gap] = word[j + gap] - 'A' + 'a';
> 
> You convert the B to b.  Why did you not use tolower the way you use
> toupper below?
Mere testing myself. 
>                     
> >                    if (isupper(word[j]))
> 
> This if evaluates to true.
> 
> >                    {
> >                        word[j] = word[j] - 'A' + 'a';
> 
> You convert A to a.
>                         
> >                        if (word[j] > word[j + gap])
> 
> This if evaluates to false
> 
> >                        {
> >                            swap(word, &gap, &j);
> >                        }
> >                        
> >                        word[j] = toupper(word[j]);
> >                    }
> >                    else if (word[j] > word[j + gap])
> 
> This if is not evaluated.
> 
> >                    {
> >                        swap(word, &gap, &j);
> >                    }
> >                    word[j + gap] = toupper(word[j + gap]);
> >                }
> >                
> >                else if (isupper(word[j]))
> 
> You have a tremendous amount of duplicated code to deal with the four
> case situations (both upper case, first upper case and second lower
> case, etc).  Consider:
>      Test each letter:
>           If upper case set a flag and convert it to lower.
>           Else reset the flag.
>      Test for swap:
>           If necessary swap the letters and the flags.
>      Test each flag:
>           If appropriate, convert corresponding letter back to upper.

I have to ponder over this; it's not clear yet. I saw that the code
was massive, but I have graphically written it out, checking if it 
works, before implementing in a program. I will need to look into it, and
more importantly at your suggestion which helps a lot to make the code
efficient. 
> 
> On the other hand, do you even need to worry about case.  Did the
> problem statement specify that B and b short sort together?  What
> would be so terrible if B sorted before a (in ASCII) or if b sorted
> before A (in EBCDIC)?
> 
My goal was to sort all letters in a given word, bar none. 

[toc] | [prev] | [next] | [standalone]


#77085

FromJames Kuyper <jameskuyper@verizon.net>
Date2015-11-24 07:09 -0500
Message-ID<n31jt4$e9m$1@dont-email.me>
In reply to#77071
On 11/24/2015 05:11 AM, Alla _ wrote:
...
>> On the other hand, do you even need to worry about case.  Did the
>> problem statement specify that B and b short sort together?  What
>> would be so terrible if B sorted before a (in ASCII) or if b sorted
>> before A (in EBCDIC)?
>>
> My goal was to sort all letters in a given word, bar none.

That doesn't answer the question. When you say "sorted", what exactly do
you mean? There's many different possibilities for the handling of case
when sorting.

0: ignore case
1: convert all letters to lower case before sorting.
2: convert all letters to upper case before sorting.
3: Sort upper case letters before lower case letters.
4: Sort lower case letters before upper case letters.

For options 3 and 4, there's an additional choice to be made:
a) sort primarily by alphabetical order, and secondarily by case
b) sort primarily by case, and secondarily by alphabetical order

Every one of those options has a context in which it's the right choice.
However, the easiest choice in C is to sort ASCII characters by their
numerical values, which corresponds to 3a, and that would be my normal
expectation in a context like this, where nothing else was specified
about the sort order. You, on the other hand, have chosen to implement
1. That strikes me as odd, if only because it made your program much
more complicated than it needed to be.
-- 
James Kuyper

[toc] | [prev] | [next] | [standalone]


#76985

FromRichard Heathfield <rjh@cpax.org.uk>
Date2015-11-23 12:26 +0000
Message-ID<n2v0h9$ddi$2@dont-email.me>
In reply to#76866
On 22/11/15 15:06, Alla _ wrote:
> <snip>
>
> Below is a program that represent only a partial implementation of a given task.

Prediction confirmed. You're going too fast, so you're not learning 
enough to make a good job of your programs.

Slow down. And re-wind.

-- 
Richard Heathfield
Email: rjh at cpax dot org dot uk
"Usenet is a strange place" - dmr 29 July 1999
Sig line 4 vacant - apply within

[toc] | [prev] | [next] | [standalone]


#76988

Fromraltbos@xs4all.nl (Richard Bos)
Date2015-11-23 13:26 +0000
Message-ID<565313e0.9653796@news.xs4all.nl>
In reply to#76985
Richard Heathfield <rjh@cpax.org.uk> wrote:

> On 22/11/15 15:06, Alla _ wrote:
> > <snip>
> >
> > Below is a program that represent only a partial implementation of a given task.
> 
> Prediction confirmed. You're going too fast, so you're not learning 
> enough to make a good job of your programs.
> 
> Slow down. And re-wind.

Yes. Alla, I once commended you for reading your own code, carefully. It
seems that you've stopped doing that. Go back. Be careful. Make sure
you've understood what you've written _completely_ before you go on to
the next problem.

Richard

[toc] | [prev] | [next] | [standalone]


#76870

FromAlla _ <modelling.data@gmail.com>
Date2015-11-22 07:17 -0800
Message-ID<8864bc3b-1f6b-47a7-bba0-33818bc259a1@googlegroups.com>
In reply to#76655
<snip>

One more note: I deliberately do not use neither fgets, not scanf for the input.

[toc] | [prev] | [next] | [standalone]


#76653

FromJames Kuyper <jameskuyper@verizon.net>
Date2015-11-20 12:15 -0500
Message-ID<564F5520.8050503@verizon.net>
In reply to#76641
On 11/20/2015 11:06 AM, Alla _ wrote:
> Hello!
> 
> Please, take a look at the function below. It is from K&R.
> 
> I dare to wonder why they use a while loop if the condition
> considers only one item in the list. ...

It does not. The loop keeps executing until getch() returns something
other than ' ' or '\t'.

> ... Why not to use if statement?

Because that would execute the getch() only once.

> What is the purpose and the logic behind the while loop in this case?
> 
> I have accidentally found confirmation of my
> concern on stackoverflow:
> 
> QUOTE:
> Lines like while ((s[0] = c = getch()) == ' ' || c == '\t'); make me wanna weep. - ammoQ
> 
> @ammoQ Indeed. And then people still recommend K&R, I have absolutely no idea why. Look at this horrible code, it is not written by the OP, it is written by K&R! Had any rookie programmer written code like this today, he would have been immediately fired. - Lundin
> 
> UNQUOTE
> 
> Function: 
> 
> /* getop: get next character or numeric operand */
> int getop(char s[])
> {
>     int i, c;
> /* the below while loop */
>     while ((s[0] = c = getch()) == ' ' || c == '\t')
>         ;

I disagree with ammoQ. Once you've learned enough about C, such code
should be quite clear. The only changes I'd make are as follows:

    while((c=getch()) == ' ' || c == '\t');
    s[0] = c;

The reason they put the ';' on a separate line is to make it more
visible - they're worried that writing loops with empty bodies the way I
prefer to write them will result in people not noticing the ';' and
correspondingly misinterpret the code. However, I often write loops with
active loop conditions (ones that can change the state of the program)
and empty bodies, and as a result I always pay close attention to a ';'
in that location. I'm quite error-prone in general, yet I can't remember
ever making the kind of mistake they're worrying about.

[toc] | [prev] | [next] | [standalone]


Page 2 of 4 — ← Prev page 1 [2] 3 4  Next page →

Back to top | Article view | comp.lang.c


csiph-web