读书人

lt;lt;21天学通C++gt;gt;例子代码异常

发布时间: 2012-12-23 11:28:15 作者: rapoo

<<21天学通C++>>例子代码错误
由美国Jesse Liberty编著,康博创作室翻译,人民邮电出版社出版的第三版的<<21天学通C++>>中有个程序例子有Bug。该例子为第八章 指针 8.12 指针算法 例子8.11 如何根据字符串分析出单词。 第204页
源码是

#include <iostream>using namespace std;bool getWords(char * string,char * word,int & wordOffset);int main(){const int bufferSize = 255;//the max length of input stringchar buffer[bufferSize+1];char word[bufferSize+1];int wordOffset = 0;cout<<"enter a string: ";cin.getline(buffer,bufferSize);while(getWords(buffer,word,wordOffset)){cout<<"got this word: "<< word <<endl;}return 0;}bool getWords(char * string,char * word,int & wordOffset){if(!string[wordOffset]){return false;}char *p1, *p2;p1=p2=string+wordOffset;for(int i=0;i<(int)strlen(p1)&&!isalnum(p1[0]);i++){p1++;}if(!isalnum(p1[0])){return false;}p2=p1;while(isalnum(p2[0])){p2++;}int len=int(p2-p1);strncpy(word,p1,len);word[len]='\0';for(int j=int(p2-string);j<(int)strlen(string)&&!isalnum(p2[0]);j++){p2++;}wordOffset=int(p2-string);return true;}


正确的程序代码应该为:
#include <iostream>using namespace std;bool getWords(char * string,char * word,int & wordOffset);int main(){const int bufferSize = 255;//the max length of input stringchar buffer[bufferSize+1];char word[bufferSize+1];int wordOffset = 0;cout<<"enter a string: ";cin.getline(buffer,bufferSize);while(getWords(buffer,word,wordOffset)){cout<<"got this word: "<< word <<endl;}return 0;}bool getWords(char * string,char * word,int & wordOffset){if(!string[wordOffset]){return false;}char *p1, *p2;p1=p2=string+wordOffset;for(int i=0;i<(int)strlen(p2)&&!isalnum(p1[0]);i++){p1++;}if(!isalnum(p1[0])){return false;}p2=p1;while(isalnum(p2[0])){p2++;}int len=int(p2-p1);strncpy(word,p1,len);word[len]='\0';for(int j=int(p2-string);j<(int)strlen(string)&&!isalnum(p2[0]);j++){p2++;}wordOffset=int(p2-string);return true;}

问题出现在第25行,把循环条件定为p1的长度,而p1在遇到非数字或字母的字符时往后移。
当连续的非数字字母字符出现的次数小于总字符串长度的一半时,程序能正常解析;
但当非数字字母字符连续出现的次数大于总字符串长度的一半时,程序无法解析。
正确的做法是,把循环条件i小于p1的长度改为p2的长度。

读书人网 >C++

热点推荐