Skip to content

Instantly share code, notes, and snippets.

@abcsharp
Created October 20, 2011 17:30
Show Gist options
  • Save abcsharp/1301739 to your computer and use it in GitHub Desktop.
Save abcsharp/1301739 to your computer and use it in GitHub Desktop.
Brainfuckインタプリタ
#include <iostream>
#include <cstring>
#include <memory>
#include <stack>
using std::cout;
using std::cin;
using std::endl;
using std::auto_ptr;
using std::stack;
const int MemorySize=30000,SourceLength=10000;
auto_ptr<unsigned char> Memory;
auto_ptr<char> Source;
unsigned char* Ptr=0;
stack<int> Brackets;
int main(void)
{
Memory.reset(new unsigned char[MemorySize]);
Source.reset(new char[SourceLength]);
while(1){
for(int i=0;i<MemorySize;i++) *(Memory.get()+i)=0;
Ptr=Memory.get();
while(!Brackets.empty()) Brackets.pop();
cout<<"Please input program.(Max length is "<<SourceLength<<")"<<endl<<">";
cin>>Source.get();
if(!strcmp(Source.get(),"x")) break;
int Length=strlen(Source.get());
for(int i=0;i<Length;i++){
char Code=*(Source.get()+i);
if(Code=='>') Ptr++;
else if(Code=='<') Ptr--;
else if(Code=='+') (*Ptr)++;
else if(Code=='-') (*Ptr)--;
else if(Code=='.') cout<<*Ptr;
else if(Code==',') cin>>*Ptr;
else if(Code=='['){
Brackets.push(i-1);
if(!*Ptr){
int Count=1;
while(++i<Length&&Count){
if(*(Source.get()+i)=='[') Count++;
else if(*(Source.get()+i)==']') Count--;
}
}
}else if(Code==']'){
if(*Ptr){
i=Brackets.top();
Brackets.pop();
}
}else{
cout<<"Oh... \""<<Code<<"\" is an illegal character.";
break;
}
}
cout<<endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment