Ben Bacarisse
3/28/2011 12:40:00 PM
Ceriousmall <divadsmall@gmail.com> writes:
> I'm just putting this out to get some general feed
> back..........................
>
> /* 2011 Ceriousmall
> This piece of code reverses the character string [s] using the
> function reverse(s) */
>
> #include <stdio.h>
>
> #define MAXLINE 1000 /* maximum input line size */
>
> /* assigns the character string to ln[] */
> int gotline(char ln[])
It's much more useful to have a function that can be told how long the
array is with a second parameter.
> {
> int c, i;
> int at_end;
>
> for (i = 0; i < MAXLINE-1 && (c = getchar()) != EOF && c != '\n'; +
> +i)
> ln[i] = c;
> at_end = c == EOF;
>
> if (c == '\n') {
> ln[i] = c;
> ++i;
> }
> ln[i] = '\0';
>
> if (at_end)
> return EOF;
> else
> return i;
The use of at_end seems a little over the top. You could eliminate it
altogether and just end the function with
return c == EOF ? EOF : i;
> }
>
> /* reverses the character string s[] */
This does not do what is says. A reader used to C will expect that all
the character are reversed, but you specifically exclude a terminating
newline.
> void reverse(char s[])
> {
> int i, x;
> char subline[MAXLINE];
>
> for (x = 0; s[x] != '\0'; ++x)
> if (s[x] == '\n') {
> i = x;
> --i;
i = x - 1;
> }
> else
> i = x;
There's no need to set i every time. In fact you should be using
strlen.
>
> for (x = 0; i >= 0; ++x && --i) {
Its clearer to write ++x, --i rather than use &&.
> subline[x] = s[i];
> subline[i] = s[x];
> }
> for (i = 0; i < x; ++i)
> s[i] = subline[i];
> }
>
> int main(void)
> {
> int return_val;
> int at_start, at_end;
> char line[MAXLINE];
>
> at_start = 0;
>
> while (at_start != EOF) {
> return_val = gotline(line);
> at_end = return_val == EOF;
> reverse(line);
> printf("\n%s", line);
> putchar('\n');
>
> if (at_end)
> at_start = EOF;
> }
> return 0;
> }
Again, rather too any extra variables for my taste and it's a shame that
the length of the string (which you know form gotline) is not used --
you end up re-scannign it in the reverse function.
<snip>
--
Ben.