0

I'm currently building a project to practice file handling and I want to declare a vector of class like array of structure and check its size so that I could append the last vector size's object to the file. Is it possible?

#include <fstream>
#include <iterator>
#include <string>
#include <vector>
using namespace std;

class test {
    public:
    string name;
    string nickName;
    string phoneNumber;
    string address;
};
vector <test> gymMember[10];

int main()
{
    gymMember[0].name = "Lukas";
    gymMember[0].nickName = "Naruto";
    gymMember[0].phoneNumber = "0123";
    gymMember[0].address = "22A";

    gymMember[1].name = "Jack";
    gymMember[1].nickName = "Eren";
    gymMember[1].phoneNumber = "0589";
    gymMember[1].address = "23A";

    // I want to check the vector size so i could append the last vector index to a file (I know this will give an error but i wanna ask how to actually find the size)
    int size = size(gymMember);
    ofstream output_file("Contact.txt", ios::app);
    // from here i want to append the last vector index to Contact.txt with the class name, nickName, phoneNumber, address
    if (output_file.is_open()) {
        output_file << gymMember[size].name << " " << gymMember[size].nickName << " " << gymMember[size].phoneNumber << " " << gymMember[size].adress << " " << endl;
    }
    output_file.close();
    return 0;
}
Yato
  • 25
  • 1
  • 3
  • Use `sizeof` instead of `size`? – Jason Aug 06 '22 at 13:35
  • `vector gymMember[10];` is an array of ten `vector`s, all empty. `vector gymMember(10);` would be a vector of ten `test`s. – molbdnilo Aug 06 '22 at 13:38
  • `vector gymMember[10];` is an array of ten different `vector` objects. It looks like you wanted a single `vector` that starts off with ten different `test` objects. If so, you wanted `vector gymMember(10);` or `vector gymMember{10};`. To find how many elements are in it, you could use its `.size()` member function, although you might be surprised to learn that that's `10`. If you want it to start at 0 and go up as you add new things to it, you need to use `push_back` or `emplace_back` instead of trying to assign through `operator[]`. – Nathan Pierson Aug 06 '22 at 13:39
  • I believe you want to start with *one* empty vector, `vector gymMembers;`, and then add elements to it. Also, the last element is `gymMembers.back()`; you don't need to care about its index. Read the introduction to `std::vector` in your favourite C++ book. – molbdnilo Aug 06 '22 at 13:41

0 Answers0