Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

K&R

Name: Anonymous 2008-06-14 19:20

K&R

Exercise 1-8. Write a program to count blanks, tabs, and newlines.

#include <stdio.h>

main()
{
    int blank, charac, tab, newline;
   
    blank = 0;
    tab = 0;
    newline = 0;
   
    printf("          | Blanks | Tabs | Newlines | \n");

    while((charac = getchar()) != EOF)
    {
        if(charac == ' ')
            {       
                ++blank;   
            }
        if(charac == '\t')
            {       
                ++tab;       
            }
        if(charac == '\n')
            {       
                ++newline;
                printf("| No. of: | %6d | %4d | %8d | \n", blank, tab, newline);
            }
    }
}


Exercise 1-9. Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.

#include <stdio.h>

main()
{
    int input_s, space, space_c;
   
    space = ' ';
    space_c = 0;
   
    while((input_s = getchar()) != EOF)
        {   
            if(input_s != space)
                {
                putchar(input_s);
                space_c = 0;
                }
            else if(input_s == space)
                {
                ++space_c;
                if(space_c == 1)
                    {
                    putchar(input_s);
                    }
                else if(space_c > 1)
                    {
                    --space_c;
                    printf("");
                    }
                }
        }
}


Using Cygwin --GCC 3.4.4, compile with following; -ansi -m32 -pedantic.

Comments on how to make it better, what is bad and what is good, please. (1.8 sucks I know.)

Name: Anonymous 2008-06-14 22:16

I'd recommend working on your coding style.

- You have a lot of empty space that doesn't need to be there. Use a tabstop of 2 or 4, and don't put the opening { on a separate line.

- It's clearer and shorter to combine declarations and initializations, so you can write: int blank=0, charac=0; rather than int blank, charac;
blank = 0;
charac = 0;


- Use switch as an alternative to if/else if/else if/...

- Don't forget the parameters to main and the return value (cf. >>17)

- It's redundant to write if(foo) {...} else if(!foo) {...} when the condition 'foo' has no side effects. Just use if(foo) {...} else {...}.

Name: Anonymous 2008-06-14 22:40

>>18
you fail, foo is not a condition, it's an expression.
fucking faggot

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List