【发布时间】:2020-03-30 13:20:28
【问题描述】:
好像我写错了我的对象,但我看过很多例子,我仍然遇到同样的问题。我做 Staff + StaffID 的原因是我可以在有意义的情况下引用该对象。 json 对象的详细信息取决于用户输入的内容
我正在使用 nlohmann/json.hpp 库
staff = {"Staff " + staffID, {
{"First Name", first_name},
{"Last Name", last_name},
{"Age", age},
{"StaffID", staffID},
{"Phone", staff_phone},
{"Skill 1", skill_1},
{"Skill 2", skill_2},
{"Skill 3", skill_3}
} };
myFile << setw(4) << staff << endl;
myFile.close();
我的 json 文件中的结果,顶部条目还可以:
[
"Staff 1",
{
"Age": 44,
"First Name": "John",
"Last Name": "Smith",
"Phone": "97345345",
"Skill 1": "Dogs",
"Skill 2": "Vet",
"Skill 3": "Grooming",
"StaffID": "1"
}
]
[
"Staff 2",
{
"Age": 38,
"First Name": "Jane",
"Last Name": "Smith",
"Phone": "9835735",
"Skill 1": "Cats",
"Skill 2": "Surgery",
"Skill 3": "Grooming",
"StaffID": "2"
}
]
更新:更多详情 该函数在一个类中,当用户选择类中的 add_info_staff 函数时,该函数在一个允许用户添加员工的菜单的 while 循环内被调用。
class infoStaff
{
protected:
json staff;
char first_name[50];
char last_name[50];
int age;
string staffID;
string staff_phone;
string skill_1;
string skill_2;
string skill_3;
public:
void add_info_staff(void)
{
ofstream myFile("staff_j.json", ios::app);
cout << "Please enter the first name: " << endl;
cin >> first_name;
cout << "Please enter the last name: " << endl;
cin >> last_name;
cout << "Please enter the age: " << endl;
cin >> age;
cout << "Please enter the staff ID: " << endl;
cin >> staffID;
cout << "Please enter the staff's phone number: " << endl;
cin >> staff_phone;
cout << "Please enter skill 1 : " << endl;
cin >> skill_1;
cout << "Please enter skill 2 : " << endl;
cin >> skill_2;
cout << "Please enter skill 3 : " << endl;
cin >> skill_3;
staff = {"Staff " + staffID, {
{"First Name", first_name},
{"Last Name", last_name},
{"Age", age},
{"StaffID", staffID},
{"Phone", staff_phone},
{"Skill 1", skill_1},
{"Skill 2", skill_2},
{"Skill 3", skill_3}
} };
myFile << setw(4) << staff << endl;
myFile.close();
}
};
【问题讨论】:
-
预期结果是
["Staff 1" , {...}, "Staff 2", {...}]吗?如果是这样,您将不得不展示更多的程序(接受用户输入、转换为 JSON 并将其写入文件的循环) -
如果对 Botje 有帮助,我会添加更多详细信息 :) 无论哪种方式都非常感谢
-
谢谢谢夫!可能需要查看数组:)