1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
|
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
struct Record
{
std::string name;
std::string telnr;
Record() {}
Record( std::string nam, std::string tel)
: name(nam), telnr(tel)
{}
};
std::istream& operator>>(std::istream& istr, Record& record)
{
getline(istr, record.name);
getline(istr, record.telnr);
return istr;
}
std::ostream& operator<<(std::ostream& ostr, const Record& record)
{
ostr << "name: " << record.name << "\n"
<< "telnr: " << record.telnr << "\n\n";
return ostr;
}
std::ofstream& operator<<(std::ofstream& of, const Record& record)
{
of << record.name << "\n" << record.telnr << "\n";
return of;
}
std::vector<Record> create(std::ostream& ostr, std::istream& istr)
{
std::vector<Record> data_set;
std::string name, telnr;
for (int n=0; n<5; ++n)
{
ostr << "Enter name: ";
std::getline(istr, name);
ostr << "Enter telnr: ";
std::getline(istr, telnr);
ostr << "\n";
data_set.push_back( Record(name,telnr) );
}
return data_set;
}
int main()
{
std::string filename = "tele.data";
// Getting names and telnrs from console input:
std::vector<Record> data_set( create(std::cout,std::cin) );
// Writing the data_set to a file:
std::ofstream output_file(filename);
if (!output_file)
{
std::cerr << "File " << filename << "couldn't opened!\n";
return 1;
}
for (auto & record : data_set)
{
output_file << record;
}
output_file.close();
// Open the data file:
std::ifstream record_file(filename);
if (!record_file)
{
std::cerr << "File " << filename << " not found!\n";
return 1;
}
// Reading the data from file:
data_set.clear();
Record record;
while ( record_file >> record)
{
data_set.push_back(record);
}
// Get the search name:
std::cout << "Enter a number to search: ";
std::string number_to_search;
std::getline(std::cin, number_to_search);
// Searching the number in the data_set
{
bool number_found = false;
for (auto & record : data_set)
{
if (record.telnr == number_to_search)
{
number_found = true;
std::cout << "Found for telnr " << number_to_search
<< ":\n" << record.name << "\n";
break;
}
}
if (number_found == false)
{
std::cout << "No name for number "
<< number_to_search << " found.\n";
}
}
return 0;
}
| |