二. 填空题(共40分)
本程序从正文文件text.in读入一篇英文短文,统计该短文中不同单词和它的出现次数,并按词典编辑顺序将单词及它的出现次数输出到正文文件word.out中.
程序用一棵有序二叉树存储这些单词及其出现的次数,一边读入一边建立.然后中序遍历该二叉树,将遍历经过的二叉树上的节点的内容输出.
程序中的外部函数
int getword(FILE* pFile,char* pszWordBuffer,int nBufferLen);
从与pFile所对应的文件中读取单词置入pszWordBuffer,并返回1;若单词遇文件尾,已无单词可读时,则返回0.
#include
#include
#include
#include
#define SOURCE_FILE "text.in"
#define OUTPUT_FILE "word.out"
#define MAX_WORD_LEN 128
typedef struct treenode
{
char szWord[MAX_WORD_LEN];
int nCount;
struct treenode* pLeft;
struct treenode* pRight;
}BNODE;
int getword(FILE* pFile,char* pasWordBuffer,int nBufferLen);
void binary_tree(BNODE** ppNode,char* pszWord)
{
if(ppNode != NULL && pszWord != NULL)
{
BNODE* pCurrentNode = NULL;
BNODE* pMemoNode = NULL;
int nStrCmpRes=0;
____(1)_____;pCurrentNode=*ppNode
while(pCurrentNode)
{
/*寻找插入位置*/
nStrCmpRes = strcmp(pszWord, ___(2)___ );pCurrentNode->nCount
if(!nStrCmpRes)
{
___(3)___; pCurrentNode->nCount++
return;
}
else
{
___(4)___; pMemoNode=pCurrentNode
pCurrentNode = nStrCmpRes>0? pCurrentNode->pRight : pCurrentNode->pLeft;
}
}
}
pCurrent=new BNODE;
if(pCurrentNode != NULL)
{
memset(pCurrentNode,0,sizeof(BNODE));
strncpy(pCurrentNode->szWord,pszWord,MAX_WORD_LEN-1);
pCurrentNode->nCount=1;
}
if(pMemoNode==NULL)
{
___(5)___; *ppNode= pCurrentNode
}
else if(nStrCmpRes>0)
{
pMemoNode->pRight=pCurrentNode;
}
else
{
pMemoNode->pLeft=pCurrentNode;
}
}
void midorder(FILE* pFile,BNODE* pNode)
{
if(___(6)___) return;!pNode||!pFile
midorder(pFile,pNode->pLeft);
fprintf(pFile,"%s %d ",pNode->szWord,pNode->nCount);
midorder(pFile,pNode->pRight);
}
void main()
{
FILE* pFile=NULL;
BNODE* pRootNode=NULL;
char szWord[MAX_WORD_LEN]={0};
pFile=fopen(SOURCE_FILE,"r");
if(pFile==NULL)
{
printf("Can't open file %s ",SOURCE_FILE);
return;
}
while(getword(pFile,szWord,MAX_WORD_LEN)==1)
{
binary_tree(___(7)___);// pRootNode,szWord
}
fclose(pFile);
pFile=fopen(OUTPUT_FILE,"w");
midorder(pFile,pRootNode);
fclose(pFile);
}
三. 附加题(每题30分,2题,共60分)
1. 从程序健壮性进行分析,下面的FillUserInfo函数和Main函数分别存在什么问题?
#include
#include
#define MAX_NAME_LEN 20
struct USERINFO
{
int nAge;
char szName[MAX_NAME_LEN];
};
void FillUserInfo(USERINFO* parUserInfo)
{
stu::cout<<"请输入用户的个数:";
int nCount=0;
std::cin>>nCount;
for(int i=0;i
{
std::cout<<"请输入年龄:";
std::cin>>parUserInfo[i]->nAge;
std::string strName;
std::cout<<"请输入姓名:";
std::cin>>strName;
strcpy(parUserInfo[i].szName,strName.c_str());
}
}
int main(int argc,char* argv[])
{
USERINFO arUserInfos[100]={0};
FillUserInfo(arUserInfos);
printf("The first name is:");
printf(arUserInfos[0].szName);
printf(" ");
return 0;
}
2. 假设你在编写一个使用多线程技术的程序,当程序中止运行时,需要怎样一个机制来安全有效的中止所有的线程?请描述其具体流程.