Playing with C

I’ve recently been watching some videos a friend of (xray) liked me to… I’ve been meaning to learn C for a while… After all, it’s a language which compiles directly to assembly, which means (at least in theory) it should be faster than things like python and Java. I’m a big fan of OO (object orientated) programming, so something procedural like C could also be something a little different for me to try out.

After a few hours (and with help from Bruce). I Finally got something which at least resembled working C code, and it checks that the user has entered a number, rather than something like “no.”, it also accepts arguments ether in the form of command line arguments or, if command line arguments are not provided it will prompt for them interactively.  I’d love some feedback on my code :), oh, I compiled it with GCC… so if it doesn’t work on other compilers then whoops :P.

Anyway, the code is below if your interested, it simply works out the area of a rectangle, so nothing fancy, but it was simply so I could have a play with C.

#include <stdio.h>

void printRectArea(int height, int width);
void requestInput(int *height, int *width);

//works out the area of a rectangle
int main(int argc, char *argv[])
{
	int rectHeight, rectWidth;

	//Did we get options on the command line?
	if(argc != 3)
	{
		requestInput(&rectHeight, &rectWidth);
	} else {
		sscanf(argv[1], "%d", &rectWidth);
		sscanf(argv[2], "%d", &rectHeight);
	}

	printRectArea(rectHeight, rectWidth);
	return 0;
}

void printRectArea(int height, int width)
{
	int area;
	area = height * width;
	printf("%d n", area);
}

void clean_stdin(void)
{
    int c;

    do
    {
        c = fgetc(stdin);
    }
    while (c != 'n' && c != EOF);
}

void requestInput(int *height, int *width)
{
	int matches;
	do{
		printf("Enter the height: ");
		matches = scanf("%d", height);
		clean_stdin();
	}while(matches == 0);

	do{
		printf("Enter the width: ");
		matches = scanf("%d", width);
		clean_stdin();
	}while(matches == 0);
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.