实验一:
#include<stdio.h>
#define MAXLINE 1000
int getline(char line[],int maxline);
void 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);
}
}
/*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){ //变量j设置为字符串的第一个字符的下标
temp=s[j]; //变量i设置为字符串的最后一个字符的下标
s[j]=s[i]; //swap the characters
s[i]=temp;
--i;
++j;
}
}
/*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函数先找到字符串S的末尾,然后从'/0'倒退一个位置,若再遇到'/n',则再倒退一个位置。
实验二:
#include<stdio.h>
#define MAXLINE 1000 //允许的输入行的最大长度
int max; //到目前为止发现的最长行的长度
char line[MAXLINE]; //当前输入行
char longest[MAXLINE]; //用于保存最长的行
int getline(void);
void copy(void);
/*打印最长的输入行:特别版本*/
main()
{
int len;
extern int max;
extern char longest[ ];
max=0;
while((len=getline( ))>0)
if(len>max){
max=len;
copy( );
}
if(max>0) //存在这样的行
printf("%s",longest);
return 0;
}
/*getline函数:特别版本*/
int getline(void)
{
int c,i;
extern char line[ ];
for(i=0;i<MAXLINE-1&&(c=getchar())!=EOF&&c!='/n';++i)
line[i]=c;
if(c=='/n'){
line[i]=c;
++i;
}
line[i]='/0';
return i;
}
/*copy函数:特别版本 */
void copy(void)
{
int i;
extern char line[],longest[];
i=0;
while((longest[i]=line[i])!='/0')
++i;
}
调试:C-free 编译未通过
[Error] D:/Backup/我的文档/C-Free/Temp/未命名4.cpp:5: error: previous external decl of `char line[1000]'
[Error] D:/Backup/我的文档/C-Free/Temp/未命名4.cpp:45: error: type mismatch with previous external decl of `char longest[]'
[Error] D:/Backup/我的文档/C-Free/Temp/未命名4.cpp:6: error: previous external decl of `char longest[1000]'