Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -----------------------------------------------------------------------
- main.cpp
- -----------------------------------------------------------------------
- #include <cassert>
- #include <sstream>
- #include "ini.h"
- using namespace std;
- int main() {
- std::istringstream input{
- "[vegetables]\n"
- "potatoes=10\n"
- "onions=1 \n"
- "\n"
- "cucumbers=12\n"
- "\n"
- "[guests] \n"
- "guest1_name = Ivan Durak\n"
- "guest2_name = Vasilisa Premudraya\n"
- "[guest black list]"};
- ini::Document doc = ini::Load(input);
- assert(doc.GetSectionCount() == 3);
- assert((doc.GetSection("vegetables"s)
- == ini::Section{
- {"potatoes"s, "10"s},
- {"onions"s, "1"s},
- {"cucumbers"s, "12"s},
- }));
- assert((doc.GetSection("guests"s)
- == ini::Section{{"guest1_name"s, "Ivan Durak"s}, {"guest2_name"s, "Vasilisa Premudraya"s}}));
- assert((doc.GetSection("dragons"s) == ini::Section{}));
- assert((doc.GetSection("guest black list"s) == ini::Section{}));
- doc.AddSection("pets"s) = ini::Section{{"nasty"s, "rat"s}};
- assert(doc.GetSectionCount() == 4);
- }
- -----------------------------------------------------------------------
- ini.h
- -----------------------------------------------------------------------
- #include <iostream>
- #include <string>
- #include <unordered_map>
- namespace ini {
- using Section = std::unordered_map<std::string, std::string>;
- class Document {
- public:
- Section& AddSection(std::string name);
- const Section& GetSection(const std::string& name) const;
- std::size_t GetSectionCount() const;
- private:
- std::unordered_map<std::string, Section> sections_;
- };
- Document Load(std::istream& input);
- }
- -----------------------------------------------------------------------
- ini.cpp
- -----------------------------------------------------------------------
- #include "ini.h"
- using namespace std;
- namespace ini {
- Section& Document::AddSection(std::string name) {
- return sections_[name];
- }
- const Section& Document::GetSection(const std::string& name) const {
- static Section section_;
- if (!(sections_.end() == sections_.find(name))) {
- return sections_.at(name);
- } else {
- return section_;
- }
- }
- std::size_t Document::GetSectionCount() const {
- return sections_.size();
- }
- Document Load(std::istream& input) {
- Document result;
- Section* section;
- for (string str;
- getline(input, str);) {
- auto it = str.find_first_not_of(' ');
- if (str.npos == it) {
- continue;
- }
- str = str.substr(it);
- if (str[0] == '[') {
- auto section_ = str.substr(1, str.find(']') - 1);
- section = &result.AddSection(section_);
- } else {
- it = str.find('=');
- string name_ = str.substr(0, str.find_last_not_of(' ', it - 1) + 1);
- str = str.substr(str.find_first_not_of(' ', it + 1));
- string value_ = str.substr(0, str.find_last_not_of(' ') + 1);
- section->insert({name_,
- value_ });
- }
- }
- return result;
- }
- }
Add Comment
Please, Sign In to add comment