Как я могу искать запись сотрудника (по имени) в текстовом файле и отображать только его данные? - PullRequest
0 голосов
/ 29 июня 2019

Я создаю программу, в которой вводю данные о многих сотрудниках и сохраняю их в текстовом файле. Как я могу сделать функцию для поиска по всему текстовому файлу и отображения единственной информации об этом сотруднике, а не чьей-либо еще? Детали всегда вводятся в режиме добавления. Я не могу использовать eof (), поскольку он будет отображать весь документ.

Это школьный проект, и мы изучили только cin и cout, а не std ::, поэтому я использую использование пространства имен std;

РЕДАКТИРОВАТЬ: ДОБАВЛЕНО ОБРАЗЕЦ ФАЙЛА ТЕКСТА

First name:Test

Last name: asdfas

Employee no: 12

(etc.)

Local Contact: 12323

***********************************************

First name:Test2

Last name: asd

Employee no: 23432

(etc.)

Local Contact: 234324

***********************************************

void hr::empdetails()       
{
    //declaring all datamembers
        char firstname [30], lastname [30], dept[30]; //etc.


    ofstream outfile;
    outfile.open ("example.txt",ios::app);

        //inputting all details
        //writing details into text file...

        outfile<<"First name:";
        outfile<<firstname;

        //...................
        outfile<<"\nLocal Contact: ";
        outfile<<localcon;
    outfile<<"\n\n*************************************************";//indicating end of employee's details
}

void hr::searchname()
{
        //what should i write here to search for a name and display all of its details
}

Ответы [ 2 ]

0 голосов
/ 29 июня 2019

В большинстве случаев метод заключается в чтении во всех полях в записи и использовании только тех полей, которые вам нужны. Чтение дополнительных полей не потребует дополнительного времени по сравнению с выполнением кода, чтобы пропустить их.

Кроме того, предпочитайте массивы (std::vector) структур параллельным массивам:

struct Employee_Record
{
  std::string first_name;
  std::string last_name;
  int id;
  //...
};
std::vector<Employee_Record> database;
Employee_Record array[32];

Вы можете упростить ввод, перегрузив operator>> для структуры:

struct Employee_Record
{
  //...
  friend istream& operator>>(istream& input, Employee_Record& er);
};
istream& operator>>(istream& input, Employee_Record& er)
{
  getline(input, er.first_name);
  getline(input, er.last_name);
  //...
  return input;
}

Ваш введенный код будет выглядеть примерно так:

std::vector<Employee_Record> database;
Employee_Record er;
while (data_file >> er)
{
  database.push_back(er);
}

Общепринятым методом является чтение всех данных, а затем обработка данных (например, поиск).

0 голосов
/ 29 июня 2019

int main()
{
	ifstream fin("look.txt");. // Here you have to provide file name

	string line; // takes a line at a time.

	int person = 1; // this increments person 

	while (getline(fin, line)) // here we are reading data line by line till eof
	{
		if (line == "***********************************************") // this is point where we increment the person variable by one ( to change person )
			person++;

		int ind = line.find_last_of(':'); // here we are finding ':' character to get fields name like First Name , Last Name ,etc..

		string cc = line.substr(0, ind); // here we get value of the fields ex:- First Name :-Sha11 ( here we fetch Sha11 .. you use this way to compare empolyees various value ,in your desired way.. )

		if (cc == "First name" || cc == "Last name" || cc == "Local Contact") ( It is looking only for some desired fields , but you might change this according to you. )
		{
			if (ind != string::npos) 
			{
				int diff = line.size() - ind - 1;

				string pa = line.substr(ind + 1, diff);
				cout << person << " : " << cc << " : " << pa << endl; // here cc stores the field's name and pa stores the field's value. here i used substr() and find() to get desired results from the string (for more details about these function look at these urls "www.cplusplus.com/reference/string/string/find/"  , "http://www.cplusplus.com/reference/string/string/substr/")..




			}
		}
	}

	return 0;
}

Это прокомментированное объяснение может помочь вам ...!

Это может решить вашу проблему ....

...