Search code examples
c++vectorstructfstream

Can't read names from a vector of structs with string members


I'm reading certain data from a file into a vector<struct>. The code is this:

#include <fstream>
#include <map>
#include <string>
#include <vector>
#include <algorithm>   

using namespace std;

int main()
{
    ifstream fin("gift1.in", ios::in);
    ofstream fout("gift1.out", ios::out);

    unsigned short NP;

    struct person
    {
        string name;
        unsigned int gave;
        unsigned int received;
    };

    vector<person> accounts;

    string tmp_name;

    fin >> NP;
    accounts.resize(NP);
    for (auto i : accounts)
    {
        fin >> tmp_name;
        fout << "Just read this name: " << tmp_name << "\n";
        i.name = tmp_name;
        i.gave = 0;
        i.received = 0;

        fout << "We have just created this person: " << i.name << ";" << i.gave << ";" << i.received << "\n";
//(1)
        // OK, this part works
    }

    fout << "Freshly created ledger:\n";
    for (auto l : accounts)
        fout << "Person: " << l.name << "; Gave: " << l.gave << ";Received " << l.received << "\n";
//irrelevant stuff further
}

The proble is that names are printed out in the (1) loop, but they're not in the ranged for loop. Why could this be?

The sample output is this:

Just_read_this_name:_mitnik We_have_just_created_this_person:_mitnik;0;0 Just_read_this_name:_Poulsen We_have_just_created_this_person:_Poulsen;0;0 Just_read_this_name:_Tanner We_have_just_created_this_person:_Tanner;0;0 Just_read_this_name:_Stallman We_have_just_created_this_person:_Stallman;0;0 Just_read_this_name:_Ritchie We_have_just_created_this_person:_Ritchie;0;0 Just_read_this_name:_Baran We_have_just_created_this_person:_Baran;0;0 Just_read_this_name:_Spafford We_have_just_created_this_person:_Spafford;0;0 Just_read_this_name:_Farmer We_have_just_created_this_person:_Farmer;0;0 Just_read_this_name:_Venema We_have_just_created_this_person:_Venema;0;0 Just_read_this_name:_Linus We_have_just_created_this_person:_Linus;0;0 Freshly_created_ledger: Person:_;_Gave:_0;Received_0 Person:_;_Gave:_0;Received_0 Person:_;_Gave:_0;Received_0 Person:_;_Gave:_0;Received_0 Person:_;_Gave:_0;Received_0 Person:_;_Gave:_0;Received_0 Person:_;_Gave:_0;Received_0 Person:_;_Gave:_0;Received_0 Person:_;_Gave:_0;Received_0 Person:_;_Gave:_0;Received_0


Solution

  • for (auto i : accounts)
    

    Each i that you get is a copy of an element in accounts. When you do i.name = tmp_name, you're only modifying this copy. You need to take a reference instead so that you can modify the elements themselves:

    for (auto& i : accounts)