Advertisement
YourMain12

Brainfuck Compiler

Jul 8th, 2023
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. // After running the compiler save your brainfuck code as .bf file and run it by opening it on the running compiler code
  2.  
  3. #include <iostream>
  4. #include <vector>
  5.  
  6. int main() {
  7.     std::vector<int> tape(30000, 0);
  8.     int ptr = 0;
  9.     std::string code;
  10.     std::cin >> code;
  11.  
  12.     int codePtr = 0;
  13.     while (codePtr < code.size()) {
  14.         char instruction = code[codePtr];
  15.         if (instruction == '>') {
  16.             ptr++;
  17.         } else if (instruction == '<') {
  18.             ptr--;
  19.         } else if (instruction == '+') {
  20.             tape[ptr]++;
  21.         } else if (instruction == '-') {
  22.             tape[ptr]--;
  23.         } else if (instruction == '.') {
  24.             std::cout << static_cast<char>(tape[ptr]);
  25.         } else if (instruction == ',') {
  26.             char input;
  27.             std::cin >> input;
  28.             tape[ptr] = static_cast<int>(input);
  29.         } else if (instruction == '[') {
  30.             if (tape[ptr] == 0) {
  31.                 int loopCount = 1;
  32.                 while (loopCount > 0) {
  33.                     codePtr++;
  34.                     if (code[codePtr] == '[') {
  35.                         loopCount++;
  36.                     } else if (code[codePtr] == ']') {
  37.                         loopCount--;
  38.                     }
  39.                 }
  40.             }
  41.         } else if (instruction == ']') {
  42.             if (tape[ptr] != 0) {
  43.                 int loopCount = 1;
  44.                 while (loopCount > 0) {
  45.                     codePtr--;
  46.                     if (code[codePtr] == ']') {
  47.                         loopCount++;
  48.                     } else if (code[codePtr] == '[') {
  49.                         loopCount--;
  50.                     }
  51.                 }
  52.             }
  53.         }
  54.         codePtr++;
  55.     }
  56.  
  57.     return 0;
  58. }
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement