gpt4 book ai didi

c++ - 有没有办法结合两个变量?

转载 作者:行者123 更新时间:2023-12-01 14:39:28 25 4
gpt4 key购买 nike

我一直在尝试让我的代码动态地将类对象分配给文件以供以后阅读,但是在获取用户输入以保存到每个不同对象方面遇到了麻烦。

我试图让用户输入他们的姓名,年龄和电话号码,并将其保存到文件中,希望以后可以使用相同的方法在文件中读取。

我尝试使用数组,但无法保存对象的所有三个字段。是否有可以使用的动态变量?

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cassert>
using namespace std;

string mName, mID, mPhoneNumber;
int id = 0;
class Student
{
public:
string mName;
string mId;
string mPhoneNumber;

Student(string id = "", string name = "", string phone = "") : mId(id), mName(name), mPhoneNumber(phone)
{}

bool operator==(const Student& obj)
{
return (mId == obj.mId) && (mName == obj.mName) && (mPhoneNumber == obj.mPhoneNumber);
}

/*
* Write the member variables to stream objects
*/
friend ostream& operator << (ostream& out, const Student& obj)
{
out << obj.mId << "\n" << obj.mName << "\n" << obj.mPhoneNumber << endl;
return out;
}
/*
* Read data from stream object and fill it in member variables
*/
friend istream& operator >> (istream& in, Student& obj)
{
in >> obj.mId;
in >> obj.mName;
in >> obj.mPhoneNumber;
return in;
}
};

int main()
{
cin >> id;
Student stud1("1", "Jack", "4445554455");
Student stud2("4", "Riti", "4445511111");
Student stud3("6", "Aadi", "4040404011");

// open the File
ofstream out("students.txt");
// Write objects to file (targets to cout)
out << stud1;
out << stud2;
out << stud3;

out.close();
// Open the File
ifstream in("students.txt");
Student student1;
Student student2;
Student student3;
// Read objects from file and fill in data
in >> student1;
in >> student2;
in >> student3;
in.close();
// Compare the Objects
assert(stud1 == student1);
assert(stud2 == student2);
assert(stud3 == student3);

cout << stud1 << endl;
cout << stud2 << endl;
cout << stud3 << endl;
return 0;
}

最佳答案

您可以通过以下方式使用 std::vector :

std::vector<Student> my_students;
for (std::size_t i = 0; i < 3; i++) {
Student tmp;
in >> tmp;
my_students.push_back(tmp);
}

关于c++ - 有没有办法结合两个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61559974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com