⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pex3_7.cpp

📁 数据结构C++代码,经典代码,受益多多,希望大家多多支持
💻 CPP
字号:
#include <iostream.h>
#include <string.h>

class Grade
{
	private:
		char name[30];
		float score;
	public:
		// constructor
		Grade(char student[], float score);
		// default constructor
		Grade(void);

		// class operations
		int Compare(char s[]);
		void Read(void);
		void Write(void);
};

// constructor. assign name and score
Grade::Grade(char student[], float score) : score(score)
{
	strcpy(name,student);
}

// default constructor. assign name the NULL string
// and score 0
Grade::Grade(void)
{
	name[0] = '\0';
	score = 0.0;
}

// compare s with name and return TRUE if they match
// and 0 if not
int Grade::Compare(char s[])
{
	return strcmp(s,name) == 0;
}

// read values for name and score
void Grade::Read(void)
{
	cout << "Enter student name  and score on separate lines" << endl;
	cin.getline(name,30,'\n');
	cin >> score;
}

// output the object data
void Grade::Write(void)
{
	cout << "Name: " << name << "  " << "score: " << score << endl;
}


// find an object whose name matches keyname
int Search(Grade Arr[], int n, char keyname[])
{
	// do a sequential search
	for (int i = 0; i < n; i++)
		// return index if there is a match
		if (Arr[i].Compare(keyname))
			return i;
	// failure. return -1
	return -1;
}

void main(void)
{
	Grade students[5] = {Grade("John",78.3), Grade("Sally",86.5),
						 Grade("Bob",58.9), Grade("Donna",98.3)};

	students[4].Read();

	cout << "Looking for John.  Search index is " 
		 << Search(students,5,"John") << endl;
		 	
		 cout << "Looking for Tom.  Search index is " 
		 << Search(students,5,"Tom") << endl;
		 	
		 cout << "Looking for Mike.  Search index is " 
		 << Search(students,5,"Mike") << endl;
}

/*
<Run>

Enter student name  and score on separate lines
Tom
75.0
Looking for John.  Search index is 0
Looking for Tom.  Search index is 4
Looking for Mike.  Search index is -1
*/

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -