操作题 1.  请使用VC6或使用[答题]菜单打开考生文件夹proj3下的工程proj3,其中定义的MyString类是一个用于表示字符串的类。假设字符串由英文单词组成,单词与单词之间使用一个空格作为分隔符。成员函数wordCount的功能是计算组成字符串的单词的个数。
    例如,字符串“dog”由1个单词组成;字符串“the quickbrown fox jumps over the lazy dog”由9个单词组成。请编写成员函数wordCount。在main函数中给出了一组测试数据,此时程序应显示:
    读取输入文件...
   
    STR1=1
    STR2=9
    要求:
    补充编制的内容写在“//********333********”与“//********666********”之间,不得修改程序的其他部分。
    注意:程序最后将结果输出到文件out.dat中。输出函数WriteToFile已经编译为obj文件,并且在本程序中调用。
    //mystring.h
    #include <iostream>
    #include <string.h>
    using namespace std;
   
    class MyString {
    public:
    MyString(const char* s)
    {
    str = new char[strlen(s)+1];
    strcpy(str, s);
    }
   
    ~MyString() { delete [] str;}
   
    int wordCount() const;
   
    private:
    char * str;
    };
   
    void writeToFile(char * , int);
   
    //main.cpp
    #include <fstream>
    #include "mystring.h"
   
    int MyString::wordCount() const
    {
    //******** 333********
    //******** 666********
    }
    int main()
    {
    char inname[128], pathname[80];
    strcpy(pathname, "");
    sprintf (inname, "in. dat", pathname);
    cout << "读取输入文件... \n\n";
    ifstream infile (inname);
    if (infile.fail ()) {
    cerr << "打开输入文件失败!";
    exit(1);
    }
    char buf[4096];
    infile.getline(buf, 4096);
    MyString str1 ("dog"), str2 ("the quick brown fox jumps over the lazy dog"), str3 (buf);
    str1.wordCount ();
    cout << "STR1 = " << str1.wordCount () << endl;
    cout << "STR2 = " << str2.wordCount() << endl << endl;
    writeToFile(pathname,str3.wordCount());
    return 0;
    }
【正确答案】if(Str==NULL) return 0;    //如字符串str为空,返回零
   int counter=1;    //给counter赋值为1
   int length=strlen(str);    //把字符串str长度赋值给length
   for(int i=0; i<length; i++)    //i从零到length-1遍历
   if(isspace(str[i]))    //如果str[i]为空格字符
   counter++;  //counter自加1
   return counter;  //返回counter;
【答案解析】[考点] 本题考查的是MyString类,其中涉及动态数组、构造函数、析构函数和const函数。
    主要考查考生对动态数组的掌握情况,计算单词个数通过计算空格数目来完成。