Advertisement
Matteogoli

BrainfuckInterpreter

Apr 18th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. using namespace std;
  2. #include <iostream>
  3. #include <cmath>
  4. #include <cstring>
  5.  
  6. void interpreta(char);
  7. void ciclo(const int);
  8. void azzera();
  9. void stampa(int *, int);
  10. void stampa(char *, int);
  11.  
  12. const int MAXDIM = 100;
  13. int cont = 0;
  14. int * a = new int [MAXDIM];
  15. char * stringa = new char [1000];
  16.  
  17. int main()
  18. {
  19.     char c;
  20.     int len;
  21.     cin.get(c);
  22.     while(c != '\n')
  23.     {
  24.         stringa[len] = c;
  25.         cin.get(c);
  26.         len++;
  27.     }
  28.     //stampa(stringa, len);
  29.     azzera();
  30.    
  31.     for(int i = 0; i < len; i++)
  32.     {
  33.         interpreta(stringa[i]);
  34.     }
  35.    
  36.     //stampa(a, MAXDIM);
  37.    
  38.     return 0;
  39. }
  40.  
  41. void interpreta(char c)
  42. {
  43.     //cout << c << " ";
  44.     cout << cont << " ";
  45.     switch(c)
  46.     {
  47.         case '>': cont++; break;
  48.         case '<': cont--; break;
  49.         case ';': cin  >> a[cont]; break;
  50.         case ':': cout << a[cont]; break;
  51.         case '[': ciclo(cont); break;
  52.     }
  53. }
  54.  
  55. void ciclo(const int n)
  56. {
  57.     char c = stringa[n+1];
  58.     int len = 0;
  59.    
  60.     while(c != ']')
  61.     {
  62.         //cout << c;
  63.         len++;
  64.         c = stringa[n+len];
  65.     }
  66.    
  67.     char * strciclo = new char [len];
  68.     for(int i = 0; i < len; i++)
  69.         strciclo[i] = a[n+i];
  70.        
  71.     //stampa(strciclo, len);
  72.    
  73.     while(a[n] > 0)
  74.     {
  75.         cont = n;
  76.         for (int i = 0; i < strlen(strciclo); i++)
  77.             interpreta(strciclo[i]);
  78.     }
  79.    
  80. }
  81.  
  82. void azzera()
  83. {
  84.     for(int i = 0; i < MAXDIM; i++)
  85.         a[i] = 0;
  86. }
  87.  
  88. void stampa(int * b, int l)
  89. {
  90.     for (int i = 0; i < l; i++)
  91.         cout << b[i];
  92. }
  93.  
  94. void stampa(char * b, int l)
  95. {
  96.     for (int i = 0; i < l; i++)
  97.         cout << b[i];
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement