正确提取到载体

Extract properly to a vector

本文关键字:提取      更新时间:2023-10-16

我制作了一个程序,可以从文本文件中读取,将组件添加到结构中,并将每个结构元素添加到向量中。问题是,由于某种原因,阅读功能似乎根本不起作用。

这是代码:

struct address
{
    string street;
    int zip;
    string city;
};
struct person
{
    string name;
    string id;
    address location;
};
istream & operator >>(istream & in, person & p)
{
    getline(in, p.name);
    getline(in, p.id);
    getline(in, p.location.street);
    return in;
}
void read_file(string filename)
{
    vector<person> persons;
    ifstream input;
    input.open(filename);
    if (!input.is_open())
    {
        cout << "File Not Found" << endl;
    }
    person temp;
    input >> temp;
    persons.push_back(temp);
    input.close();
    if (persons.size() == 0)
    {
        cout << "The are no contacts" << endl;
    }
    else cout << "There are" << " " << persons.size() << " " << "contacts in the file" << endl;
}

文本文件中的行如下所示:

Test Name Surname
Id 1234567890
Adress, postcode, city

当我说它不起作用时,我的意思是读取函数不显示向量中是否有元素。

这是文本文件:名称.txt

主代码:

int _tmain(int argc, _TCHAR* argv[])
{
const string filename = "C://Users/TEMP/Desktop/lab1/names.txt";
int userinput = 0;

while (true)
{

    cout << "Menu: n1) Sök del av  personnamnn2) Sök stadern3) Exit" <<  endl;
    cin >> userinput;
    cout << endl;
    if (userinput == 1)
    {
        namnsok;
    }
        else if (userinput == 2)
        {
            stadsok;
        }
            else if (userinput == 3)
            {
                break;
            }
}

return 0;
}

我不得不改变行 input.open(filename);input.open(filename.c_str(),ifstream::in);让它为我工作。不过,您只会从输入中读取第一人称。