菜鸟一个,刚刚学c,在看The C Programming Language 第二版,
想通过作者提供的例子,更好的理解,结果第四章的例子完全实现不了作者
的意图,找了3个版本的书参考,都没有办法理解,百度也没有答案
1,main函数里面的found 是干吗用的?看着是一个计数器,但是作为return 的
返回值,就没有做其他用了,没见过这种用法,查了资料,返回给系统一个不是0
的值,就是异常?告诉系统这个程序是异常的?
2,作者原意是输入一段字符串,然后程序可以把含有“ould”的行打印出来,
但是这个getline()里面有一个判断,c != '\n',如果换行getline()就终止了,
接着就打印出来了,就无法像作者表述的那样,输入多行,然后筛选出需要的行
3,我想如果真的要实现作者的意图,是不是要改?strindex()筛选出来以后,另外保存,EOF以后再打印,才能够实现作者的想法?
菜鸟一个,多多指教,谢谢各路大神!
```#include <stdio.h>
#define MAXLINE 1000 /* maximum input line length */
int getline(char line[], int max)
int strindex(char source[], char searchfor[]);
char pattern[] = "ould"; /* 需要筛选的行字符串*/
/* 筛选指定字符串 */
main()
{
char line[MAXLINE];
int found = 0;/*这个是干嘛用的?*/
while (getline(line, MAXLINE) > 0)
if (strindex(line, pattern) >= 0) {
printf("%s", line);
found++;
}
return found;
}
/* getline: 输入行,返回长度*/
int getline(char s[], int lim)
{
int c, i;
i = 0;
while (--lim > 0 && (c=getchar()) != EOF && c != '\n')/*这里判断有回车
就执行下面的操作了,不可能输入多行,实际测试就是回车就开始打印*/
s[i++] = c;
if (c == '\n')
s[i++] = c;
s[i] = '\0';
return i;
}
/* strindex: 比较字符串,如果有就返回i,没有就返回没有*/
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;
}

实际效果就是输入一行有指定字符串就打印,没有就不打印
无法实现作者所说的输入多行,打印符合条件的多行
因为是这本书影响太大,所以很重视!谢谢指教!
以下代码是将对输入一行的数据立即进行检查是否存在“olud”,如果要一次检查多行数据,则需要对所以的输入行进行存储,可以在二维数组里,也可以先存储在文件中,再进行读取判断
#include <stdio.h>
#include <string.h>
#define MAXLES 801 //每行输入容纳的最大字符个数
char* s_gets(char* st, int n);
int main(void)
{
char in_lines[MAXLES];
printf("Please enter your text (Press [Enter] at the start of a line to quit)\n");
while (s_gets(in_lines, MAXLES) != NULL && in_lines[0] != '\0')
{
if (strstr(in_lines, "ould") != NULL)
puts(in_lines);
puts("Please enter next line text:");
}
return 0;
}
char* s_gets(char* st, int n) //该函数从标准输入读取一行数据,将末尾的换行符转为空字符
{
char* ret_val;
char* find;
ret_val = fgets(st, MAXLES, stdin);
if (ret_val)
{
find = strchr(st, '\n');
if (find)
*find = '\0';
else
{
while (getchar() != '\n')
continue;
}
}
return ret_val;
}