练习1-19 编写函数reverse(s),将字符串s中的字符顺序颠倒过来。使用该函数编写一个程序,每次颠倒一个输入行中的字符顺序

来源:互联网 发布:为什么需要软件测试 编辑:程序博客网 时间:2024/04/25 01:14
#include <stdio.h>#define MAXLINE 1000int getline(char s[],int lim);void reverse(char to[],char from[]);main(){    int len;    char line[MAXLINE];    char reverse_line[MAXLINE];    while((len=getline(line,MAXLINE))>0){        reverse(reverse_line,line);        printf(reverse_line);    }}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;           ++j;        }    }    if(c=='\n'){        s[j]=c;        ++j;        ++i;    }    s[j]='\0';    return i;}void reverse(char to[],char from[]){    int i,j;    i=0;    while(from[i]!='\0')        ++i;    --i;    j=0;    while(i>=0){        to[j]=from[i];        ++j;        --i;    }    to[j]='\0';}

输入abc,输出多了一行空格,原因在于\n颠倒到开头了

abccba

修改函数体、函数声明和函数调用

void reverse(char s[]){    int i,j;    char temp;    i=0;    while(s[i]!='\0')        ++i;    --i;    if(s[i]=='\n'){        --i;    }    j=0;    while(j<i){        temp=s[j];        s[j]=s[i];        s[i]=temp;        --i;        ++j;    }}
0 0
原创粉丝点击