Lignum

HQ9+ Interpreter

Oct 11th, 2014
293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <regex>
  4.  
  5. void printLyrics() {
  6.     for (int i = 99; i > 0; --i) {
  7.         std::cout << i << (i == 1 ? " bottle" : " bottles") << " of beer\n";
  8.         std::cout << "you take one down, pass it around,\n";
  9.         std::cout << ((i - 1) == 0 ? "no more" : std::to_string(i - 1)) << " bottles of beer on the wall.\n\n";
  10.     }
  11. }
  12.  
  13. void processLetter(char c, const std::string& source) {
  14.     switch (c) {
  15.     case 'h':
  16.         std::cout << "Hello World.\n";
  17.         break;
  18.  
  19.     case 'q':
  20.         std::cout << source << "\n";
  21.         break;
  22.  
  23.     case '9':
  24.         printLyrics();
  25.         break;
  26.  
  27.     case '+':
  28. #ifdef _MSC_VER
  29.         _asm {
  30.             inc eax
  31.         }
  32. #else
  33.         __asm__("inc %eax")
  34. #endif
  35.         break;
  36.     }
  37. }
  38.  
  39. void interpret(const std::string& source) {
  40.     std::string src = source;
  41.     std::regex spaces("\\s+");
  42.     std::regex_replace(src, spaces, "");
  43.  
  44.     for (auto it = src.begin(); it != src.end(); ++it) {
  45.         char c = *it;
  46.         processLetter(c, source);
  47.     }
  48. }
  49.  
  50. void runFile(const std::string& filename) {
  51.     std::ifstream in(filename);
  52.     std::string line;
  53.     std::string source;
  54.  
  55.     while (std::getline(in, line)) {
  56.         source += line;
  57.     }
  58.  
  59.     interpret(source);
  60. }
  61.  
  62. void runConsole() {
  63.     while (true) {
  64.         std::string input;
  65.  
  66.         std::cout << "> ";
  67.         std::cin >> input;
  68.  
  69.         if (input.empty()) {
  70.             continue;
  71.         }
  72.  
  73.         interpret(input);
  74.     }
  75. }
  76.  
  77. int main(int argc, char** argv) {
  78.     if (argc == 1) {
  79.         runConsole();
  80.     } else if (argc == 2) {
  81.         runFile(argv[1]);
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment