Cookbook

Copy a file

#include <stdio.h>

int main() {
	int c;
	c = getchar();

	while (c != EOF) {
		putchar(c);
		c = getchar();
	}
}

or

while((c = getchar()) != EOF)
	putchar(c);

Count characters in input

int main(void) {
	long nc;

	nc = 0;

	while(getchar() != EOF)
		++nc;
	printf("%ld\n",nc);
}

Line couting

int main(void) {
	int c, nl;

	nl = 0;

	while((c = getchar()) != EOF)
		if(c == '\n')
			++nl;

	printf("%d\n", nl);
}

Word counting

#include <stdio.h>

#define IN 1
#define OUT 0

main()
{
	int c, nl, nw, nc, state;

	state = OUT;
	nl = nw = nc = 0;
	while((c = getchar()) != EOF)
	{
		++nc;

		if(c == '\n')
			++nl;
		if (c == ' ' || c == '\n' || c == '\t')
			state = OUT;
		else if (state == OUT) {
			state = IN;
			++nw;
		}
	}

	printf("%d %d %d\n", nl, nw, nc);
}

Count the number of occurrences of each digit

#include <stdio.h>

int main()
{
	int c, i, nwhite, nother;
	int ndigit[10];

	nwhite = nother = 0

	for(i = 0; i < 10; ++i)
		ndigit[i] = 0;

	while((c = getchar()) != EOF) {
		if (c >= '0' && c <= '9')
			++ndigit[c-'0']; // Get the numeric value of this digit
		else if (c == ' ' || c == '\n' || c == '\t')
			++nwhite;
		else
			++nother;
	}

	printf("digits =");
	for(i = 0; i < 10; ++i)
		printf(" %d", ndigit[i]);
	printf(", white space = %d, other = %d\n", nwhite, nother)
}
Written on September 15, 2017