Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/EmptyTag/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 无法从包含字符串成员的结构向量中读取名称_C++_Vector_Struct_Fstream - Fatal编程技术网

C++ 无法从包含字符串成员的结构向量中读取名称

C++ 无法从包含字符串成员的结构向量中读取名称,c++,vector,struct,fstream,C++,Vector,Struct,Fstream,我正在将文件中的某些数据读入向量。代码如下: #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

我正在将文件中的某些数据读入向量。代码如下:

#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
}
问题是名称在1循环中打印出来,但它们不在范围for循环中。 为什么会这样

示例输出如下所示:

只要读一下这个名字:mitnik 我们刚刚创造了这个人:米尼克;0;0 只要读一下这个名字:Poulsen 我们刚刚创造了这个人:鲍尔森;0;0 只要读一下这个名字:\u Tanner 我们刚刚创造了这个人:\u Tanner;0;0 只需读一下这个名字:\u Stallman 我们刚刚创造了这个人:\u Stallman;0;0 只需读一下这个名字:\u Ritchie 我们刚刚创造了这个人:里奇;0;0 只要读一下这个名字:"巴兰" 我们刚刚创造了这个人:巴拉恩;0;0 只要读一下这个名字:\u Spafford 我们刚刚创造了这个人:斯帕福德;0;0 只要读一下这个名字:\农民 我们刚刚创造了这个人:农民;0;0 读一下这个名字:\维尼玛 我们刚刚创造了这个人:维尼玛;0;0 只要读一下这个名字:\u Linus 我们刚刚创造了这个人:\u Linus;0;0 新创建的\u分类账: 人:_给出:_0;已收到0 人:_给出:_0;已收到0 人:_给出:_0;已收到0 人:_给出:_0;已收到0 人:_给出:_0;已收到0 人:_给出:_0;已收到0 人:_给出:_0;已收到0 人:_给出:_0;已收到0 人:_给出:_0;已收到0 人:_给出:_0;已收到0

您得到的每个i都是帐户中某个元素的副本。当您执行i.name=tmp_name时,您只需修改此副本。您需要采用引用,以便可以修改图元本身:

for (auto& i : accounts)

这对我来说应该是显而易见的。不过还是要谢谢你。
for (auto& i : accounts)