第四章:函数与程序结构
4.1
#include <stdio.h>
#define MAXLINE 1000 /* 定义最大输入行长度*/
/*this is example program*/
/* find the line that have the specified string*/
int getlines(char line[],int max);
int strindex(char source[],char searchfor[]); /* 两个函数原型*/
char pattern[] = "ould"; /* the string that we want to find*/
/* 声明字符数组 pattern,并赋值。全局变量。需要查找的字符串。*/
main()
{
char line[MAXLINE]; /*声明字符数组,line,存储输入字符串。*/
int found = 0; /* 声明整型变量,found,记录需要查找的字符串出现的次数*/
while (getlines(line,MAXLINE) >0)
if (strindex (line,pattern)>=0){
printf("%s",line);/* 寻找到需要的字符串,输出,计数 变量,found +1*/
found++;
}
return found;/* main函数 未声明类型,默认为整型*/
}
/* getlines save one line to s and return the length of the line */
int getlines (char s[],int lim) /* 把一行字符存储在 s[] 中,返回值是字符串的长度*/
{
int c,i;
i=0;
while (--lim > 0 && (c=getchar()) != EOF && c!= '\n')/*
--lim > 0 // 对读取的总长度进行限制,以免访问数组越界。 (c=getchar()) != EOF // 是否读取到文件末尾,文件读完毕,即使没有读到最大长度也结束了。 c!= '\n') // 是否是换行,读取到换行也意味着结束。 */
s[i++] = c;
if (c == '\n')
s[i++] = c;
s[i] = '\0';
return i;
}
/* strindex function:return the string t 's place in the string s,if not
found .return -1.*/
int strindex( char s[], char t[])
{
int i,j,k;
for (i = 0;s[i] != '\0';i++){
for (j=i,k=0;t[k] !='\0' && s[j]==t[k];j++,k++)
;
if (k > 0 && t[k] == '\0')
return i;
}
return -1;
}