C character arrays (K&R exercice 1-17)

Back on the K&R book, still working through the ‘Tutorial Introduction’ and in the character array section. Here is my solution to Exercise 1-17: print out all lines with 80 or more characters.

#include <stdio.h> 
#define MAXLINE 1000

// This line has over 80 characters qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq

int countchar(char line[], int maxline);

int main(int argc, char *argv[]){

	char line[MAXLINE];
	int len;

	while ((len = countchar(line,MAXLINE)) > 0){
		if(len > 80)
			printf("%s", line);
	}

}

int countchar(char s[], int lim){
	int i, c;
	for(i = 0; (c = getchar()) != EOF && c != '\n' && i < lim - 1; ++i){
		s[i] = c;
	}
	if(c == '\n'){
		s[i] = '\n';
		i++;
	}
	s[i] = '\0';

	return i;
}

// This line has exaclty 80 chars =============================================
// This line has exaclty 81 chars ==============================================

A bit of explanation: The main function calls the countchar() function which returns the number of characters in the array. If the return value is more than 80, the the main function prints the ‘line[]’ array populated by the countchar() function during its execution. The main() function calls the countchar() function until it gets a ‘0’ response. The output of the program (again I piped the source file back through to provide some data) is as follows:

# ./over80 < over80.c 
// This line has over 80 characters qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq
// This line has exaclty 81 chars ==============================================
This entry was posted in C and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *