Add File-reading and helper-methods for phonebook

This commit is contained in:
Matti 2024-11-01 21:25:09 +01:00
parent 290c9e2a53
commit c27a71a56f

View File

@ -125,16 +125,62 @@ void saveAllContacts(std::vector<Kontaktdaten*> *Telefonbuch, std::string *fileN
outfile.close();
}
int exponentiate(int base, int exponent) {
int result = 1;
while (exponent > 0) {
result *= base;
exponent--;
}
return result;
}
int intStringToInt(std::string input) {
int result = 0;
int size = input.length();
for(int i = 0; i < size; i++) {
int digit = input[size - 1 - i] - '0'; // -1 to consider 0-index // -'0' to get ascii indicies right
result += digit * exponentiate(10, i); // shift digit
}
return result;
}
void readContactsFromFile(std::vector<Kontaktdaten*> *Telefonbuch, std::string *fileName) {
std::ifstream infile;
infile.open(*fileName);
Kontaktdaten person;
infile >> person.firstName >> person.lastName;
infile >> person.number;
if (!infile.is_open()) {
std::cout << "File does not exist" << std::endl;
}
std::string line;
int counter = 0;
Kontaktdaten * personpointer = new Kontaktdaten;
while (std::getline(infile, line)) {
int attribute = counter % 3;
counter++;
switch (attribute) {
case 0:
personpointer->firstName = line;
break;
case 1:
personpointer->lastName = line;
break;
case 2:
personpointer->number = intStringToInt(line);
addContact(personpointer, Telefonbuch);
personpointer = new Kontaktdaten;
break;
default:
std::cout << "This should never happen" << std::endl;
}
}
infile.close();
addContact(&person, Telefonbuch);
}
/*
@ -153,6 +199,11 @@ void TelefonbuchMain() {
std::string fileName = "../IO-Files/Telefonbuch.txt";
std::vector<Kontaktdaten*> Telefonbuch;
for (int i=0; i<1; i++) {
readContactsFromFile(&Telefonbuch, &fileName);
std::cout << "Done with reading " << i << std::endl;
}
auto * Robin = new Kontaktdaten;
auto * Saxo = new Kontaktdaten;
auto * Jesus = new Kontaktdaten;
@ -169,11 +220,25 @@ void TelefonbuchMain() {
Jesus->firstName = "Jesus";
Jesus->lastName = "Nazarett";
/*
*Robin->number = 123456;
Robin->firstName = "Robin der Neue";
Robin->lastName = "Schnaiter";
Saxo->number = 987654;
Saxo->firstName = "Saxobastian";
Saxo->lastName = "Broschianer";
Jesus->number = 6666666;
Jesus->firstName = "Jesus";
Jesus->lastName = "Nazarett";
*/
addContact(Robin, &Telefonbuch);
addContact(Saxo, &Telefonbuch);
addContact(Jesus, &Telefonbuch);
printAllContacts(&Telefonbuch);
// printAllContacts(&Telefonbuch);
saveAllContacts(&Telefonbuch, &fileName);
delete Robin;