Created
January 4, 2012 14:22
-
-
Save abcsharp/1560244 to your computer and use it in GitHub Desktop.
brainfuckインタプリタ(短くなった)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <map> | |
#include <functional> | |
#include <array> | |
int main(void) | |
{ | |
std::map<const char,std::function<void(void)>> Ops; | |
std::array<unsigned char,30000> Source,Memory; | |
auto Position=Source.cbegin(); | |
auto Ptr=Memory.begin(); | |
Ops.insert(std::make_pair('>',[&]{Ptr++;})); | |
Ops.insert(std::make_pair('<',[&]{Ptr--;})); | |
Ops.insert(std::make_pair('+',[&]{(*Ptr)++;})); | |
Ops.insert(std::make_pair('-',[&]{(*Ptr)--;})); | |
Ops.insert(std::make_pair('.',[&]{std::cout<<*Ptr;})); | |
Ops.insert(std::make_pair(',',[&]{*Ptr=std::cin.get();while(std::cin.get()!='\n');})); | |
Ops.insert(std::make_pair('[',[&]{if(!*Ptr) for(int n=1;*(++Position)&&n;) *Position=='['?n++:*Position==']'?n--:n;})); | |
Ops.insert(std::make_pair(']',[&]{if(*Ptr) for(int n=1;--Position!=Source.cbegin()&&n;) *Position=='['?n--:*Position==']'?n++:n;})); | |
while(true){ | |
Memory.fill(0); | |
Position=Source.cbegin(); | |
Ptr=Memory.begin(); | |
std::cout<<"Please input program.(Max length is "<<Source.max_size()<<")"<<std::endl<<">"; | |
std::cin.getline((char*)Source.data(),Source.max_size()); | |
if(Source[0]=='x'&&!Source[1]) break; | |
do{ | |
try{ | |
Ops.at(*Position)(); | |
}catch(...){ | |
std::cout<<"Oh... \""<<*Position<<"\" is an illegal character."; | |
break; | |
} | |
}while(*(++Position)); | |
std::cout<<std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment