C/C++ - Машина Тьюринга

Ответить
Аватара пользователя
mego4el

C/C++ - Машина Тьюринга

Сообщение mego4el »

Доброго времени суток.

Есть программа которая реализует на МТ Небольшое вычисление, приведение из унарной в десятичную.



Никак не могу разобраться с ошибками, пожалуйста помогите поисправлять.



Выдает ошибки:



[BCC32 Error] Unit1.h(54): E2285 Could not find a match for 'string::basic_string(const string&)'

Full parser context

Unit1.cpp(7): #include Unit1.h

Unit1.h(31): class TuringMachine

Unit1.h(564): decision to instantiate: void TuringMachine::WriteLog()

--- Resetting parser context for instantiation...

Unit1.h(53): parsing: void TuringMachine::WriteLog()

[BCC32 Error] Unit1.h(65): E2451 Undefined symbol 'Memo2'

Full parser context

Unit1.cpp(7): #include Unit1.h

Unit1.h(31): class TuringMachine

Unit1.h(564): decision to instantiate: void TuringMachine::WriteLog()

--- Resetting parser context for instantiation...

Unit1.h(53): parsing: void TuringMachine::WriteLog()

[BCC32 Error] Unit1.cpp(29): E2285 Could not find a match for 'TuringMachine::TuringMachine()'

Full parser context

Unit1.cpp(16): parsing: _fastcall TForm1::TForm1(TComponent *)

[BCC32 Error] Unit1.cpp(39): E2451 Undefined symbol 'StartConf'

Full parser context

Unit1.cpp(37): parsing: void _fastcall TForm1::Button1Click(TObject *)



Код таков:



Unit.cpp





Код:

Код: Выделить всё

// ---------------------------------------------------------------------------
#include 
#pragma hdrstop
#include 
#include 
#include 
#include "Unit1.h"
// ---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
TMemo *Memo1;
TMemo *Memo2;
using namespace std;
// ---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) {
    Memo1->Lines->Clear();
    Memo1->Lines->Add("1..9 : десятичные цифры");
    Memo1->Lines->Add("/ : унарная цифра");
    Memo1->Lines->Add("+ : сложение");
    Memo1->Lines->Add("^ : местонахождение головки");
    Memo1->Lines->Add("* : умножение");
    Memo1->Lines->Add("- : урезанная разница");
    // TuringMachine * machine = new TuringMachine();
    //AnsiString s = ;
    //string str = AnsiString(s.c_str());
    TuringMachine machine;
    //TuringMachine("//////////3///////"); //StartConf
}
// ---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
    if (machine == null)
        machine = new TuringMachine(StartConf.Text);
    machine.DecimalToUnary();
    machine.UnaryToDecimal();
    //richTextBox1.Text = machine.tb.Text;
}
// ---------------------------------------------------------------------------

Unit.h





Код:

Код: Выделить всё

//---------------------------------------------------------------------------
#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published:    // IDE-managed Components
    TLabel *Label1;
    TEdit *Edit1;
    TMemo *Memo1;
    TMemo *Memo2;
    TButton *Button1;
    void __fastcall Button1Click(TObject *Sender);
private:    // User declarations
public:        // User declarations
    __fastcall TForm1(TComponent* Owner);
};
// ---------------------------------------------------------------------------
class TuringMachine : public TForm
{
    short state; // состояние q
    char * tape; // = new char[512] длина ленты
    int pointer; // головка, или указатель позиции на ленте
    public:
    TuringMachine(string _configuration)
    {
        tape = new char[512]; // выделяем память, задаем начальную конфигурацию
        pointer = 250; //256
        for (short i = 0; i < _configuration.length(); i++)
        {
            // собираем начальную конфигурацию(опускаем пробелы)
            if (_configuration[i] != 32)
                tape[pointer++] = _configuration[i];
        }
        //переводим обратно в нач состояние, после сборки
        pointer = 250;
        // tb = new RichTextBox(); -- Memo2
    }
    void WriteLog()
    {
        string str = new string('_',2);
        for (int i = 220; i < 330; i++)
            if (tape[i] != '\0')
            {
                if (i == pointer)
                    str += (char)94; // записываем ^
                str += tape[i];
            }
        str += "__\n";
        // tb.Text += str;
        //Memo2->Text += str;
        Memo2->Lines->Add(str);
    }
    // инверсное движение - имитируем движение ленты, а не головки
    void MoveLeft(){pointer++; WriteLog();}
    void MoveRight(){pointer--; WriteLog();}
    char Read() {return tape[pointer];}
    void Write(char _inp) {
        tape[pointer] = _inp;
        WriteLog();
    }
    void DecimalToUnary() {
        state = 1; // q1 разрешение на выполнение
        while (state != 0) {
            switch(state) {
            case 1:
                switch(Read()) {
                default:
                    MoveLeft();
                    break;
                case '\0':
                    Write('#');
                    state = 2;
                    continue; // окончание итерации произойдет вместе со сменой режима
                }
                break;
                // ***********************************
            case 2:
                switch(Read()) {
                default:
                    MoveRight();
                    break;
                case '\0':
                    MoveLeft();
                    state = 3;
                    continue;
                }
                break;
                // ***********************************
            case 3:
                switch(Read()) {
                case '2':
                    Write('\0');
                    MoveLeft();
                    Write('\0');
                    state = 6;
                    continue;
                case '+':
                    Write('\0');
                    state = 5;
                    MoveLeft();
                    continue;
                case '#':
                    Write('\0');
                    state = 10;
                    continue;
                case '/':
                    Write('\0');
                    state = 4;
                    MoveLeft();
                    continue;
                }
                break;
                // ***********************************
            case 4:
                switch(Read()) {
                case '\0':
                    Write('/');
                    state = 2;
                    continue;
                default:
                    MoveLeft();
                    break;
                }
                break;
                // ***********************************
            case 5:
                switch(Read()) {
                case '\0':
                    Write('+');
                    state = 2;
                    continue;
                default:
                    MoveLeft();
                    break;
                }
                break;
                // ***********************************
            case 6:
                switch(Read()) {
                case '\0':
                    MoveLeft();
                    state = 7;
                    continue;
                default:
                    MoveRight();
                    break;
                }
                break;
                // ***********************************
            case 7:
                switch(Read()) {
                case '9':
                    Write('8');
                    state = 8;
                    continue;
                case '8':
                    Write('7');
                    state = 8;
                    continue;
                case '7':
                    Write('6');
                    state = 8;
                    continue;
                case '6':
                    Write('5');
                    state = 8;
                    continue;
                case '5':
                    Write('4');
                    state = 8;
                    continue;
                case '4':
                    Write('3');
                    state = 8;
                    continue;
                case '3':
                    Write('2');
                    state = 8;
                    continue;
                case '2':
                    Write('1');
                    state = 8;
                    continue;
                case '1':
                    Write('\0');
                    state = 8;
                    MoveLeft();
                    continue;
                case '-':
                    Write('\0');
                    state = 9;
                    MoveLeft();
                    continue;
                }
                break;
                // ***********************************
            case 8:
                switch(Read()) {
                case '\0':
                    Write('/');
                    MoveLeft();
                    Write('/');
                    state = 6;
                    continue;
                default:
                    MoveLeft();
                    break;
                }
                break;
                // ***********************************
            case 9:
                switch(Read()) {
                case '\0':
                    Write('-');
                    state = 2;
                    continue;
                default:
                    MoveLeft();
                    break;
                }
                break;
                // ***********************************
            case 10:
                switch(Read()) {
                case '\0':
                    MoveLeft();
                    Write('\0');
                    MoveLeft();
                    state = 11;
                    continue;
                default:
                    MoveRight();
                    break;
                }
                break;
                // ***********************************
            case 11:
                switch(Read()) {
                case '/':
                    MoveLeft();
                    break;
                case '+':
                    Write('/');
                    MoveRight();
                    state = 12;
                    continue;
                }
                break;
                // ***********************************
            case 12:
                switch(Read()) {
                case '/':
                    MoveRight();
                    break;
                case '-':
                    state = 17;
                    continue;
                case '\0':
                    MoveLeft();
                    Write('\0');
                    MoveLeft();
                    state = 13;
                    continue;
                }
                break;
                // ***********************************
            case 13:
                switch(Read()) {
                case '/':
                    MoveLeft();
                    break;
                case '-':
                    MoveLeft();
                    break;
                case '\0':
                    MoveRight();
                    state = 14;
                    continue;
                }
                break;
                // ***********************************
            case 14:
                switch(Read()) {
                case '/':
                    Write('\0');
                    MoveRight();
                    state = 15;
                    continue;
                case '-':
                    Write('\0');
                    MoveRight();
                    state = 16;
                    continue;
                }
                break;
                // ***********************************
            case 15:
                switch(Read()) {
                case '/':
                    MoveRight();
                    break;
                case '-':
                    MoveRight();
                    break;
                case '\0':
                    MoveLeft();
                    state = 12;
                    continue;
                }
                break;
                // ***********************************
            case 16:
                switch(Read()) {
                case '/':
                    MoveRight();
                    break;
                case '\0':
                    Write('/');
                    state = 0;
                    continue;
                }
                break;
                // ***********************************
            case 17:
                switch(Read()) {
                default:
                    Write('\0');
                    MoveLeft();
                    break;
                case '\0':
                    MoveRight();
                    state = 0;
                    continue;
                }
                break;
            }
        }
    }
Аватара пользователя
mego4el

Re: C/C++ - Машина Тьюринга

Сообщение mego4el »

Разобрался!



Еще вопрос



Бралось из исходников на C#, и тут какое-то значение маски:



this.StartConf.Mask = "&&&&&&&&&&+2*0-&&&&&&&&&&";

Для последующего

this.StartConf.Text = "//////////3///////";



Как это преобразовать на C++? Подскажите пожалуйста :wacko



И еще один:



Сейчас программа запускается, но выдает ошибку Violation при нажатии кнопки расчета.

Сделал преобразование из string в UnicodeString, но не пойму что же ему не нравится =\







В коде вот что:



Unit1.h



Код:

Код: Выделить всё

class TuringMachine
{
	short state; // состояние q
	char * tape; // = new char[512] длина ленты
	int pointer; // головка, или указатель позиции на ленте
	public:
	TuringMachine(string _configuration)
	{
		tape = new char[512]; // выделяем память, задаем начальную конфигурацию
		pointer = 250; //256
		for (short i = 0; i < _configuration.length(); i++)
		{
			// собираем начальную конфигурацию(опускаем пробелы)
			if (_configuration[i] != 32)
			{
				tape[pointer++] = _configuration[i];
			}
		}
		// переводим обратно в нач состояние, после сборки
		pointer = 250;
		//tb = new RichTextBox(); -- Memo2
	}
	void WriteLog()
	{
		//string str = new string('_',2);
		string str(2,'_');
		for (int i = 220; i < 330; i++)
			if (tape[i] != '\0')
			{
				if (i == pointer)
					str += (char)94; // записываем ^
				str += tape[i];
			}
		str += "__\n";
		// tb.Text += str;
		//AnsiString anstr = str.c_str();
		UnicodeString unstr = str.c_str();
		Memo2->Lines->Add(unstr);
	}
//...
//...

Unit1.cpp





Код:

Код: Выделить всё

TForm1 *Form1;
TMemo *Memo1;
TMemo *Memo2;
using namespace std;
TuringMachine machine("//////////3///////"); //startconf
////////////+2*3-///////
//this.StartConf.Mask = "&&&&&&&&&&+2*0-&&&&&&&&&&";
// ---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner)
{
	Memo1->Lines->Clear();
	Memo1->Lines->Add("1..9 : десятичные цифры");
	Memo1->Lines->Add("/ : унарная цифра");
	Memo1->Lines->Add("+ : сложение");
	Memo1->Lines->Add("^ : местонахождение головки");
	Memo1->Lines->Add("* : умножение");
	Memo1->Lines->Add("- : урезанная разница");
	Memo2->Text="";
}
// ---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
	machine.DecimalToUnary();
	machine.UnaryToDecimal();
	//richTextBox1.Text = machine.tb.Text;
	//Memo2->Text = machine.Read();
}
Ответить

Вернуться в «Программирование и базы данных»