Interpreter Brainfucka - wypisuje śmieci
Ostatnio zmodyfikowano 2016-04-20 17:43
polewa Temat założony przez niniejszego użytkownika |
Interpreter Brainfucka - wypisuje śmieci » 2016-04-20 16:38:34 Witam. Piszę interpreter brainfucka: #include <iostream> #include <fstream>
std::string read( std::fstream && file ) { std::string temp; std::string ret; while( file >> temp ) ret += temp; return ret; }
int main( int argc, char ** argv ) { if( argc == 1 ) { std::cerr << "Enter path to the *.by file\nPress any key to exit..."; std::cin.get(); return 1; } std::fstream file( argv[ 1 ] ); if( !file ) { std::cerr << "Unable to open file\nPress any key to exit..."; std::cin.get(); return 2; } char data[ 1000 ]; char * dp = data; std::string code = read( std::move( file ) ); size_t it = 0; size_t nor = 0; while( it < code.size() ) { switch( code[ it ] ) { case '>': ++dp; break; case '<': --dp; break; case '+': ++( * dp ); break; case '-': ++( * dp ); break; case '.': std::cout <<* dp; break; case ',': std::cin >>* dp; break; case '[': if( * dp == 0 ) { int lc = 1; while( lc != 0 ) { ++it; if( code[ it ] == '[' ) ++lc; if( code[ it ] == ']' ) --lc; } } else nor = it; break; case ']': it = nor - 1; break; default: break; } ++it; } std::cout << "\nExecution time: TODO\nPress any key to exit..."; std::cin.get(); } Testuje na tym kodzie: ++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>. Ale za każdym razem wypisuje śmieci(i za każdym razem inne). Na przykład: ╝╩ĐĐďń╦ďÎŢňňÍ Proszę o pomoc i z góry dzięki. |
|
pekfos |
» 2016-04-20 17:16:18 Pamięć nie jest wyzerowana. |
|
polewa Temat założony przez niniejszego użytkownika |
» 2016-04-20 17:43:14 Błąd był tutaj: case '-': ++( * dp ); break; Zamiast inkrementacji powinna być deinkrementacja. Ostateczny kod: #include <iostream> #include <fstream>
std::string read( std::fstream && file ) { std::string temp; std::string ret; while( file >> temp ) ret += temp; return ret; }
int main( int argc, char ** argv ) { if( argc == 1 ) { std::cerr << "Enter path to the *.by file\nPress any key to exit..."; std::cin.get(); return 1; } std::fstream file( argv[ 1 ] ); if( !file ) { std::cerr << "Unable to open file\nPress any key to exit..."; std::cin.get(); return 2; } char data[ 1000 ] = { 0 }; char * dp = data; std::string code = read( std::move( file ) ); file.close(); size_t it = 0; size_t nor = 0; while( it < code.size() ) { switch( code[ it ] ) { case '>': ++dp; break; case '<': --dp; break; case '+': ++( * dp ); break; case '-': --( * dp ); break; case '.': std::cout <<* dp; break; case ',': std::cin >>* dp; break; case '[': if( * dp == 0 ) { int lc = 1; while( lc != 0 ) { ++it; if( code[ it ] == '[' ) ++lc; if( code[ it ] == ']' ) --lc; } } else nor = it; break; case ']': it = nor - 1; break; default: break; } ++it; } std::cout << "\nExecution time: TODO\nPress any key to exit..."; std::cin.get(); } |
|
« 1 » |