stamen

Stamen - static menu generator
git clone git://git.dimitrijedobrota.com/stamen.git
Log | Files | Refs | README | LICENSE

stamen.cpp (1431B)


      1 #include <cmath>
      2 #include <format>
      3 #include <iostream>
      4 
      5 #include "stamen/stamen.hpp"
      6 
      7 #include "stamen/menu.h"
      8 
      9 namespace stamen {
     10 
     11 int builtin_display(const char* title, const item_t itemv[], size_t size)
     12 {
     13   const auto items  = std::span(itemv, size);
     14   const size_t dgts = static_cast<size_t>(std::log10(size)) + 1;
     15   int choice        = 0;
     16 
     17   while (true)
     18   {
     19     std::cout << std::format("{}:\n", title);
     20     for (auto i = 0UL; i < size; i++)
     21     {
     22       std::cout << std::format(" {:{}}. {}\n", i, dgts, items[i].prompt);
     23     }
     24 
     25     while (true)
     26     {
     27       std::cout << "Choose an option: ";
     28       if (std::cin >> choice && choice >= -1
     29           && choice < static_cast<int>(size))
     30       {
     31         if (choice == -1)
     32         {
     33           std::cout << "Choice: back\n";
     34           return 1;
     35         }
     36 
     37         const auto uchoice = static_cast<size_t>(choice);
     38         std::cout << "Choice: " << items[uchoice].prompt << "\n\n";
     39         const int res = items[uchoice].callback(uchoice);
     40 
     41         if (res < 2) break;
     42         return res - 1;
     43       }
     44 
     45       if (std::cin.eof())
     46       {
     47         std::cerr << "encountered end of input!\n";
     48         return std::numeric_limits<int>::max();
     49       }
     50 
     51       std::cin.clear();
     52       std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
     53       std::cout << "Invalid option, please choose again!\n";
     54     }
     55     std::cout << std::endl;
     56   }
     57 
     58   return 1;
     59 }
     60 
     61 }  // namespace stamen