Aug 26, 2016

K & R : Exercise 1.19 - Reverse input line

K & R : Exercise 1.19 - Reverse input line

Problem Statement

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.


Solution

As the problem suggest we need to reverse the input line-wise. We need to write a function that would reverse a line. We need to store the entire line in buffer, lets do in variable buf, which can store max length l.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_BUF_LEN 1000

void swap(char *a, char *b) {
  char temp;
  temp = *a;
  *a = *b;
  *b = temp;
  return;
}

void reverse(char *s)
{
  int len = strlen(s);
  int i;

  for(i = 0; i < len / 2; i++) {
    swap(&s[i], &s[len-i-1]);
  }
  return;
}
int main()
{
  int ch;
  char buf[MAX_BUF_LEN] = {0,};
  int idx = 0;
  while((ch = getchar()) != EOF) {
    if(ch != '\n') {
      /* Buffer the line */
      buf[idx] = ch;
      idx++;
      if(idx >= MAX_BUF_LEN) {
        printf("ERROR: No buf remaining\n");
        exit(0);
      }
    }else {
      buf[idx] = '\0';
      reverse(buf);
      puts(buf);
      idx = 0;
    }
  }
  return 0;
}

No comments :

Post a Comment