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
|
struct LandDetails
{ // declaring a class
public:
string Surname, OtherNames, LandNum, KraPin, OwnerIdCard, address, LandCounty,
LandDist, LandDiv, Landloc, LandSubloc;
//function will read a file into a vector, a line is searched that
//correspond user input, the record found is modified by a string,
//the file so modified is passed to another vector and written
//back to file. The function is doing, but appends the record at
//end of file (duplication of record), how do i modify the
//function to overwrite that record only and leave the other
//records intact ?
void modify_record();
};
int
main()
{
LandDetails openner;
openner.modify_record();
system("pause");
return 0;
}
void
LandDetails::modify_record()
{
LandDetails obj;
std::fstream inFile("Lands File.txt"); //open text file in read mode
std::cout << "Please enter the individual's Surname whose Land you want to search " <<
endl;
std::getline(cin, obj.Surname);
std::cout << "Enter owner KRA pin\n";
getline(cin, obj.KraPin);
std::string::size_type found;
std::vector < std::string > old_file; //will hold old file being read to memory
std::vector < std::string > modified_data; //will hold modified file containing
string new_line = "Registrar : Transferred"; //a string that will be added to line
std::string line = "";
if (!inFile) {
std::cout << "File not opened\n";
return;
}
while (std::getline(inFile, line)) { //reading file line by line into a string variable
{
old_file.push_back(line);
} //reading into a vector container
inFile.close();
for (size_t i = 0; i < old_file.size(); i++) { //searching for the record through the file already in memory
if ((found = line.find(obj.Surname, 0))
&& (found = line.find(obj.KraPin, 0) != string::npos))
std::cout << "\n" << obj.
Surname << " of KRA Number " << obj.KraPin <<
" record found with the following details: \n\n" << line << '\n';
//after record is found, it is concatenated with the string value
line = line + "," + new_line;
modified_data.push_back(old_file[i] + line); //am including the modification
}
ofstream writer("Lands File.txt", ios::app); //if i omit the ios::app flag, everything gets overwritten and only
// the rectified record is written to file----advise since i wont remove this flag
if (!writer) {
cout << "Failed to open file for writing";
}
for (size_t j = 0; modified_data.size(); j++) {
writer << modified_data[j] << endl << endl;
} //then writing back everything to file
writer.close();
}
}
|