Я бы сохранил аэропорты в массиве следующим образом:
{
"airports": [{
"address": "Horley, Gatwick RH6 0NP, UK",
"city": "London",
"shortVersion": "(LGW)"
},
{
"address": "Marupe, LV-1053",
"city": "Riga",
"shortVersion": "(RIX)"
}
]
}
Упорядочены массивы в json, см .: json.org .Затем вы будете использовать индекс, введенный пользователем, для доступа к нужному аэропорту.
Редактировать: Индекс подразумевается в зависимости от порядка аэропорта в массиве json.«Лондон» будет индексом 0, «Рига» 1 и т. Д.
Код доступа к аэропорту будет зависеть от используемой вами библиотеки json.Псевдокод для этого будет выглядеть примерно так:
int user_selection = 1; // Whatever number the user picked...
JsonArray airports = json["airports"];
JsonObject airport = airports[user_selection]; // Index the array based on user's input
airport["city"] = "Amsterdam"; // Change city from Riga to Amsterdam
Edit2: Использование библиотеки json nlohmann:
#include "json.hpp"
#include <iostream>
#include <string>
std::string GenerateJson(const std::string& city, const std::string& address, const std::string& iata_code)
{
json j;
json j_array = json::array();
json j_object = json::object();
j_object["city"] = city;
j_object["address"] = address;
j_object["shortVersion"] = iata_code;
j_array.emplace_back(j_object);
j["airports"] = j_array;
return j.dump(4);
}
int main()
{
auto json = R"(
{
"airports": [{
"address": "Horley, Gatwick RH6 0NP, UK",
"city": "London",
"shortVersion": "LGW"
},
{
"address": "Marupe, LV-1053",
"city": "Riga",
"shortVersion": "RIX"
}
]
}
)"_json;
int index = 1;
auto& airports = json["airports"];
for (const auto& airport : airports)
{
std::cout << index << ") " << airport["city"].get<std::string>() << " " << airport["shortVersion"].get<std::string>() << std::endl;
++index;
}
int choice = 0;
std::cout << "Your choice:" << std::endl;
std::cin >> choice;
choice -= 1;
std::string iata_code;
std::cout << "Change IATA airport code:" << std::endl;
std::cin >> iata_code;
auto& airport = airports[choice];
airport["shortVersion"] = iata_code;
std::cout << json.dump(4) << std::endl;
int any;
std::cout << "Press any key to exit..." << std::endl;
std::cin >> any;
}