《C程序设计语言》第4章第一个例题:
要把输入进来的所有带“ould”的行给输出回去。可是无论输入的是什么,都不会输出。
#include <stdio.h>
#define MAX_INPUT 1000
#define PARTEN "ould"
int get_line(char line[], int max)
{
char ch;
int i = 0;
while(--max > 0 && (ch = getchar()) != EOF && ch != '\n')
{
line[i++] = ch;
}
if(ch == '\n')
{
line[i++] = ch;
}
line[i] = '\0';
return i;
}
int string_index(char string[], char word[])
{
int i, j, k;
for(i = 0; string[i] != '\0'; i++)
{
for(j = i, k = 0; word[k] != '\0' && string[j] == word[k]; j++, i++)
{
;
}
if(k > 0 && word[k] == '\0')
{
return i;
}
}
return -1;
}
int main()
{
char line[MAX_INPUT];
int found = 0;
while(get_line(line, MAX_INPUT) > 0)
{
if(string_index(line, PARTEN) >= 0)
{
printf("%s", line);
found++;
}
}
return found;
}
