请使用VC6或使用【答题】菜单打开考生文件夹proj3下的工程proj3,其中定义的MyString类是一个用于表示字符串的类。假设字符串由英文单词组成,单词与单词之间使用一个空格作为分隔符。成员函数wordCount的功能是计算组成字符串的单词的个数。

admin2015-06-27  30

问题 请使用VC6或使用【答题】菜单打开考生文件夹proj3下的工程proj3,其中定义的MyString类是一个用于表示字符串的类。假设字符串由英文单词组成,单词与单词之间使用一个空格作为分隔符。成员函数wordCount的功能是计算组成字符串的单词的个数。
例如,字符串“dog”由1个单词组成;字符串“thequickbrownfoxjumpsoverthelazydog”由9个单词组成。请编写成员函数wordCount。在main函数中给出了一组测试数据,此时程序应显示:
读取输入文件…
STR1=1
STR2=9
要求:
补充编制的内容写在“//**********333**********”与“//**********666**********”之间,不得修改程序的其他部分。
注意:程序最后将结果输出到文件out.dat中。输出函数WriteToFile已经编译为obj文件,并且在本程序中调用。
//mystring.h
#include
#include
usingnamespacestd;
classMyString{
public:
MyString(constchar*s)
{
str=newchar[strlen(S)+1];
strcpy(str,S);
};
—MyString(){delete[]str;)
intwordCount()const;
private:
char*str;
};
voidwriteToFile(char。,int);
//main.cpp
#include
#include”mystring.h”
intMyString::wordCount()const
{
//********333********
//********666********
}
intmain()
{
charinname[128],pathname[80];
strcpy(pathname,"");
sprintf(inname,"in.dat",pathname);
cout<<"读取输入文件…\n\n";
ifstreaminfile(inname);
if(infile.fail()){
cerr<<"打开输入文件失败!";
exit(1);
}
charbuf[4096];
infile.getline(buf,4096);
MyStringstr1("dog"),str2("thequickbrownfoxjumpsoverthelazydog"),str3(buf);
str1.wordCount();
cout<<"STR1="<cout<<"STR2="<writeToFile(pathname,str3.wordCount());
return0;
}

选项

答案if (str == NULL) return 0; int counter = 1; int length = strlen(str); for (int i = 0; i < length; i++) if (isspace(str[i])) counter++; return counter;

解析 主要考查考生对动态数组的掌握情况,计算单词个数通过计算空格数目来完成。
转载请注明原文地址:https://jikaoti.com/ti/RnE0FFFM
0

最新回复(0)