Re: HELP!! Two questions from <<the c programming language>>
- From: Ben Bacarisse <ben.usenet@xxxxxxxxx>
- Date: Thu, 31 May 2007 18:11:35 +0100
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>
<snipped>
My program of exercise 1-9
#include <stdio.h>
int main()
{
}
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.
.
- References:
- HELP!! Two questions from <<the c programming language>>
- From: Tak
- Re: HELP!! Two questions from <<the c programming language>>
- From: Ian Collins
- Re: HELP!! Two questions from <<the c programming language>>
- From: Tak
- Re: HELP!! Two questions from <<the c programming language>>
- From: Guru Jois
- Re: HELP!! Two questions from <<the c programming language>>
- From: Tak
- Re: HELP!! Two questions from <<the c programming language>>
- From: Ben Bacarisse
- Re: HELP!! Two questions from <<the c programming language>>
- From: Guru Jois
- HELP!! Two questions from <<the c programming language>>
- Prev by Date: Re: How to print in C
- Next by Date: Re: I've read K&R, what now?
- Previous by thread: Re: HELP!! Two questions from <<the c programming language>>
- Next by thread: Re: HELP!! Two questions from <<the c programming language>>
- Index(es):
Relevant Pages
|