Skip to content

Instantly share code, notes, and snippets.

@shaobin0604
Created October 28, 2009 13:17
Show Gist options
  • Save shaobin0604/220481 to your computer and use it in GitHub Desktop.
Save shaobin0604/220481 to your computer and use it in GitHub Desktop.
tcpl_ex-1-19.c
/*
* 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>
#define MAXLINE 1000
void reverse(char line[]);
int getline(char line[], int maxline);
int main(void)
{
char line[MAXLINE];
while (getline(line, MAXLINE) > 0)
{
reverse(line);
printf("%s", line);
}
return 0;
}
int getline(char line[], int maxline)
{
int c, i, j;
i = j = 0;
while ((c = getchar()) != EOF && c != '\n')
{
if (i < maxline - 2)
{
line[i++] = c;
}
j++;
}
if (c == '\n')
{
line[i++] = '\n';
j++;
}
line[i] = '\0';
return j;
}
void reverse(char line[])
{
int i, j;
char tmp;
i = j = 0;
while (line[j] != '\0')
++j;
if (line[--j] == '\n')
--j;
while (i < j)
{
tmp = line[i];
line[i] = line[j];
line[j] = tmp;
--j;
++i;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment