Skip to content

Instantly share code, notes, and snippets.

@kamiyaowl
Last active March 28, 2019 05:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamiyaowl/c4d8bb95795f1ca775b8a86b684d3a27 to your computer and use it in GitHub Desktop.
Save kamiyaowl/c4d8bb95795f1ca775b8a86b684d3a27 to your computer and use it in GitHub Desktop.
Brainf**k in c++ https://ideone.com/GkS1L6
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <stdint.h>
using namespace std;
int main() {
vector<uint8_t> mem(30000,0);
stack<int> branchStack;
string src;
cin >> src;
int ptr = 0;
int pc = 0;
for(pc = 0; pc < src.length() ; ++pc) {
// cout << pc << ":" << src[pc] << endl;
switch(src[pc]) {
case '+':
mem[ptr]++;
break;
case '-':
mem[ptr]--;
break;
case '>':
ptr++;
break;
case '<':
ptr--;
break;
case ',':
cin >> mem[ptr];
break;
case '.':
cout << (char)mem[ptr];
break;
case '[':
if (mem[ptr]) {
branchStack.push(pc - 1);
} else {
for(int nest = 1 ; nest > 0 && pc < src.length() - 1 ; ++pc) {
switch(src[pc + 1]) {
case '[':
nest++;
break;
case ']':
nest--;
break;
}
}
}
break;
case ']':
pc = branchStack.top();
branchStack.pop();
break;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment