Continuing to slowly progress through The C Programming Language by Brian Kernighan and Dennis Ritchie.
The code I came up with below is for Exercise 1-19 - Write a function reverse(s) that reverses the character string s. Use it to write a program that reverses its input a line at a time.
Feedback is much appreciated.
// Exercise 1-19. Write a function reverse(s) that reverses the character string s. // Use it to write a program that reverses its input a line at a time. #include <stdio.h> void reverseLine(char *s); void reverseLine(char *s) { int count; count = 0; for (int i = 0; s[i] != '\0'; i++) { count++; } for (int j = count - 1; j >= 0; j--) { putchar(s[j -1]); } putchar('\n'); } int main() { int ch, charCount; char line[BUFSIZ]; charCount = 0; while ((ch = getchar()) != EOF) { if (charCount >= BUFSIZ - 1) { fprintf(stderr, "Overly long line ignored.\n"); while ((ch = getchar()) != EOF && ch != '\n') { ; } line[charCount] = ch; charCount = 0; continue; } line[charCount++] = ch; if (ch == '\n') { line[charCount++] = '\0'; reverseLine(line); charCount = 0; } } }