这段代码是如何工作的?请帮我理解这个实验室程序? [英] How this code is working? Please help me understand this lab program?
本文介绍了这段代码是如何工作的?请帮我理解这个实验室程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include <cstdio>
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
using namespace std;
class node
{
public:
char name[20],usn[20];
node *link;
};
node *h[29];
void insert()
{
char name[20],usn[20],buffer[50];
fstream out;
out.open("stud.txt",ios::out | ios::app);
if(!out)
{
cout<<"\nNot able to open";
return;
}
cout<<"\n Enter name:";
cin>>name;
cout<<"Enter Usn:";
cin>>usn;
strcpy(buffer,name);
strcat(buffer,"|");
strcat(buffer,usn);
strcat(buffer,"\n");
out<<buffer;
out.close();
}
void hash_insert(char name1[],char usn1[],int hash_key)
{
node *p,*prev,*curr;
p=new node;
strcpy(p->name,name1);
strcpy(p->usn,usn1);
p->link=NULL;
prev=NULL;
curr=h[hash_key];
if(curr==NULL)
{
h[hash_key]=p;
return;
}
while(curr!=NULL)
{
prev=curr;
curr=curr->link;
}
prev->link=p;
}
void retrieve()
{
fstream in;
char name[20],usn[20];
int j,count;
node *curr;
in.open("stud.txt",ios::in);
if(!in)
{
cout<<"\nNot able to open";
exit(0);
}
while(!in.eof())
{
in.getline(name,20,'|');
in.getline(usn,20,'\n');
count=0;
for(j=0;j<strlen(usn);j++)
{
count=count+usn[j];
}
count=count%29;
hash_insert(name,usn,count);
}
in.close();
cout<<"Enter Usn:";
cin>>usn;
count=0;
for(j=0;j<strlen(usn);j++)
count=count+usn[j];
count=count%29;
curr=h[count];
if(curr==NULL)
{
cout<<"\n Record not found";
return;
}
do
{
if(strcmp(curr->usn,usn)==0)
{
cout<<"\n Record found:"<<curr->usn<<"\t"<<curr->name;
curr=curr->link;
return;
}
else
{
curr=curr->link;
}
}
while(curr!=NULL);
if(curr==NULL)
{
cout<<"\n Record not found";
return;
}
}
int main()
{
int ch;
for( ; ; )
{
cout<<"\n1.Insert\t 2.Retrieve\t 3.Exit\n";
cout<<"Enter the choice:";
cin>>ch;
switch(ch)
{
case 1:insert(); break;
case 2:retrieve(); break;
case 3:return 0;
}
}
}
我尝试了什么:
这个代码是如何工作的?请帮我理解这个实验室程序?
What I have tried:
how this code is working? please help me understand this lab program?
推荐答案
为什么要关注老式的,C
-like,代码?
无论如何你可以理解它执行代码的静态分析:尝试(从心理上)从主函数开始遵循程序执行(作为先决条件你应该知道C ++
),这种方式你应该能够掌握一般情况。如果您对细节有疑问,请在此处询问具体问题。
Why bother about old fashioned,C
-like, code?
Anyway you could understand it performing static analysis of the code: try to (mentally) follow program execution starting from the main function (as a pre-requisite you should knowC++
), this way you should be able to grasp the general picture. Then if you have doubts on details, ask here specific question.
这篇关于这段代码是如何工作的?请帮我理解这个实验室程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文