想不明白,向前辈求教,小程序改错
本来是想写一个类似于文本编辑器“查找与替换”的简单功能,但我发现我写的这个单词查找方法findw()有一个问题,是这样,查找单词没问题,查找字母好像也没问题,但在查找字母a时就有问题.... 不能完全查找到所有的a,调试发现在findw()的while()中word数组的内容被改变了,为什么呢?想不明白,请大家多多指点一下,告诉我错在哪里~环境:MS Visual C++ 6.0
程序代码:
#include<stdio.h> #include<stdlib.h> #include<string.h> // 测试文本 char str[1024]="When we are children, there are lots of people ask about our dreams, and our answers most are doctors, policemen, teachers etc. But when we grow up, we have to face the reality, not everyone would realize childhood dreams, and some of these dreams even are unrealistic which will never be able to achieve. Therefore, we need correctly treat the relationship between dream and reality."; // 打印查找结果 void display(int* index,int wlen) { char mark_start=16; char mark_end=17; char* sp=str; int* ip=index; int m=0; while(*sp!='\0') { if(m==*ip) { putchar(mark_start); } if(m==*ip+wlen) { putchar(mark_end); ip++; } putchar(*sp); sp++; m++; } } // 查找单词 void findw() { char word[20]={0}; // 用于保存要查找单词 int index[20]={0}; // 用于保存查找单词在文本中出现的位置 char* p=str; char* wp=word; printf("\n请输入您想查找的单词: "); scanf("%s",&word); while(getchar()!='\n'); printf("您要查找的单词为: %s\n",word); int j=0; while(*p!='\0') { if(*p==*wp) { wp++; } else { wp=word; if(*p==*wp) { wp++; } } if(*wp=='\0') { index[j++]=p-str-strlen(word)+1; wp=word; } p++; } printf("查找的单词数为%d个\n",j); if(j!=0) { printf("是否用标记在文中显示?(y/n)"); char c=getchar(); while(getchar()!='\n'); if(c=='y') { display(index,strlen(word)); } } } int main(int argc,char* argv[]) { // test while(1) { findw(); } return 0; }