A simple concept yet I seem to have written it in a complicated way.
I have written some C++ source code that should:
- write what will be read in later(I do not need the writing, only for reading in later)
- read in a file
- parse it
- save the data to a class
- print out all the saved class data
I am absolutely new to C++ and OOP and Programming and English.
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
class Person {
private:
    int age;
    std::string name;
public:
    void setAge(int age) {
        this->age = age;
    }
    int getAge() {
        return age;
    }
    void setName(std::string name) {
        this->name = name;
    }
    std::string getName() {
        return name;
    }
    void printInfo() {
        std::cout
            << "Name: " << getName() << '\n'
            << "Age: " << getAge() << '\n';
    }
};
std::istream& operator>> (std::istream& is, Person& person) {
    int age;
    is >> age;
    std::string name;
    is >> name;
    person.setAge(age);
    person.setName(name);
    return is;
}
int main() {
    auto myfilename = "unknown-people.txt";
    std::ofstream myfile(myfilename, std::ios::binary | std::ios::trunc);
    myfile << "3 Baby\n";
    myfile << "48 Linus Torvalds\n";
    myfile << "62 Bill Gates\n";
    myfile << "115 Kane Tanaka\n";
    myfile.close();
    std::ifstream mysamefile(myfilename, std::ios::binary);
    std::string details;
    std::vector<Person> people;
    while (std::getline(mysamefile, details)) {
        Person person;
        std::istringstream personDetails(details);
        personDetails >> person;
        people.push_back(person);
    }
    mysamefile.close();
    for (std::vector<Person>::iterator it = people.begin(); it != people.end(); ++it) {
        it->printInfo();
        if (!(it != people.end() && it == --people.end())) {
            std::cout << "\n\n";
        }
    }
}