exc/k&r/01-a-tutorial-introduction/01-19.c

62 lines
1.1 KiB
C
Raw Normal View History

#include <stdio.h>
#define MAXLINE 1000
void reverse(char s[]);
int mystrlen(char s[]);
int get_line(char s[], int maxline);
/* reverses input line by line */
int main()
{
int end = 0;
char line[MAXLINE + 1];
while (end != EOF) {
end = get_line(line, MAXLINE);
reverse(line);
printf("%s", line);
if (end != EOF)
putchar(end);
}
}
/* reverses string 's' in place */
void reverse(char s[])
{
char c;
int i, len = mystrlen(s);
for (i = 0; i < len / 2; ++i) {
c = s[i];
s[i] = s[len-i-1];
s[len-i-1] = c;
}
}
/* returns length of string 's' */
int mystrlen(char s[])
{
int len;
for (len = 0; s[len] != '\0'; ++len)
;
return len;
}
/* reads (possibly truncated) line from input to s, returns \n or EOF */
int get_line(char s[], int maxline)
{
int c, i;
for (i=0; (c=getchar()) != EOF && c != '\n'; ++i) {
if (i < maxline)
s[i] = c;
}
if (i < maxline)
s[i] = '\0';
else
s[maxline] = '\0';
return c;
}