I need to make a program that stores usernames and passwords. I want to store them in json file. I already made a program that kinda does that, but it deletes old inputs and rewrite them as new.
int main()
{
char pass[12];
char user[12];
std::ofstream o;
o.open("logins.json");
json j;
system("cls");
std::cout << "Username: ";
std::cin >> user;
std::cout << "Password: ";
std::cin >> pass;
j[user]["Username"] = user;
j[user]["Password"] = pass;
o << std::setw(4) << j << std::endl;
}
So for example we input username: admin, password: admin. It creates a json file and stores them:
{
"admin": {
"Username": "admin",
"Password": "admin"
}
}
But when I run the program again and this time input username:user, password:user, it replaces admin with user. So basically it stores only one input. But I need it to store all of them. So I later can access them.
And that's not good. Can you please help me fix this or suggest something else?
Every time you run this application it rewrites file logins.json
ignoring its existing contents.
If you would like to edit the json file, you need to load it first, decode json, modify json, and serialize the json back into the file overwriting it.
E.g.:
int main() {
json j;
{
std::ifstream i("logins.json");
if(i.is_open())
i >> j;
}
system("cls");
std::string pass;
std::string user;
std::cout << "Username: ";
std::cin >> user;
std::cout << "Password: ";
std::cin >> pass;
j[user]["Username"] = user;
j[user]["Password"] = pass;
std::ofstream o("logins.json");
o << std::setw(4) << j << '\n';
}