Re: HELP!! Two questions from <<the c programming language>>



Guru Jois <guru.jois@xxxxxxxxx> writes:

On May 31, 6:04 pm, Ben Bacarisse <ben.use...@xxxxxxxxx> wrote:
Tak <kakat...@xxxxxxxxx> writes:
Algorithm trim_space

<bad algorithm snipped>


My program of exercise 1-9

#include <stdio.h>

int main()
{
<snipped>
}

It seems run OK,without error or warning in Vc++6.0.
Does it still contain any problems?

Yes. What happens when the input ends with one or more spaces?


yet smaller code..

#include<stdio.h>
main() {

int c;
int flag;

flag = 0;

while ((c = getchar ()) != EOF) {
if (c == ' ') {
if (!flag) {
flag = 1;
putchar (c);
}
}
else {
flag = 0;
putchar (c);
}
}

}

I'd write it:

#include <stdio.h>

int main(void)
{
int c;
char last_char = '\n'; /* Anything that is not a space */
while ((c = getchar()) != EOF) {
if (c != ' ' || last_char != ' ')
putchar(c);
last_char = c;
}
return 0;
}

because I am not a fan of flag variables and this pattern is very
useful for all sorts of filtering and counting programs.

--
Ben.
.



Relevant Pages

  • Re: [usb-storage] Re: RFC drivers/usb/storage/libusual
    ... int rc; ... +static void usu_disconnect ... This flag is only needed when we're in high-speed, ...
    (Linux-Kernel)
  • Re: [RFC PATCH 0/6] Convert all tasklets to workqueues
    ... int flag; ... static void do_test ... The difference between softirqs and hardirqs lays not in their "heavyness". ...
    (Linux-Kernel)
  • Re: Linux Serial Programming
    ... >int written, bytesRead; ... You are using the O_NDELAY flag to allow the port to be opened, ... then retrieved the current configuration. ... And one more flag *must* be set. ...
    (comp.os.linux.development.apps)
  • Re: CryptRL 0.6340 first ASCII release
    ... 'entite' has an asociated unique behavior, ... class Zombie extends Being implements Undead {... ... you implement a flag that takes space in the Zombie class but not in the Orc ... I will simply use a int classId to replace getClass.getName, ...
    (rec.games.roguelike.development)
  • Re: ignore a line
    ... int main ... Without a terminating newline in the printf string, ... You would set a flag before beginning the copy, ... clear the flag and skip writing that line to the destination file. ...
    (alt.comp.lang.learn.c-cpp)