码迷,mamicode.com
首页 > 其他好文 > 详细

C - The C Answer (2nd Edition) - Exercise 1-19

时间:2015-07-27 23:00:48      阅读:135      评论:0      收藏:0      [点我收藏+]

标签: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        /* maximum input line size */

int getline(char line[], int maxline);
int reverse(char s[]);

/* reverse input lines, a line at a time */
main()
{
	char line[MAXLINE];     /* current input line */

	while((getline(line, MAXLINE)) > 0)
	{
		reverse(line);
		printf("%s", line);
	}
}

/* getline: read a line into s, return length */
int getline(char s[], int lim)
{
	int c, i, j;
	j = 0;
	for(i = 0; (c = getchar()) != EOF && c != '\n'; ++i)
	{
		if(i < lim - 2)
		{
			s[j] = c;       /* line still in boundaries */
			++j;
		}
	}
	if(c == '\n')
	{
		s[j] = c;
		++j;
		++i;
	}
	s[j] = '\0';
	return i;
}

/* reverse: reverse string s */
void reverse(char s[])
{
	int i, j;
	char temp;
	i = 0;
	while(s[i] != '\0')     /* find the end of string s */
	{
		++i;
	}
	--i;                    /* back off from '\0' */
	if(s[i] == '\n')
	{
		--i;                /* leave newline in place */
	}
	j = 0;                  /* beginning of new string s */
	while(j < i)
	{
		temp = s[j];
		s[j] = s[i];        /* swap the characters */
		s[i] = temp;
		--i;
		++j;
	}
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

C - The C Answer (2nd Edition) - Exercise 1-19

标签:exercise 1-19

原文地址:http://blog.csdn.net/troubleshooter/article/details/47092143

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!