Разработка транслятора на языке Си

Дипломная работа - Компьютеры, программирование

Другие дипломы по предмету Компьютеры, программирование



>CString szOut - Результирующая строка. Необходима для вывода содержимого исходного файла и результатов транслирования в диалоговое окно программы. Функции и процедуры:

ATL::CString::Append(CString str) - Данная функция добавляет строку str в конец текущей строки.

ATL::CString::AppendChar(char chr) - Данная функция добавляет символ chr в конец текущей строки.

ATL::CString::Find(CString str) - Ищет первое совпадение в текущей строке с символами строки str. Функция возвращает порядковый номер первого символа совпавшей комбинации.::CString::Delete(int k, const 1) - Удаляет колличество символов, указонное во втором аргументе, начиная с k-го символа.::CString::Insert(int k, CString str) - Вставляет подстроку str в текущую строку начиная с символа k.::CString::GetLength() - Возвращает длину текущей строки.

. Листинг программы

Заголовочный файл приложения p2c.h

// p2c.h : main header file for the PROJECT_NAME application

//

#pragma once

#ifndef __AFXWIN_H__

#error "include 'stdafx.h' before including this file for PCH"

#endif

#include "resource.h"// main symbols

// Cp2cApp:

// See p2c.cpp for the implementation of this class

//Cp2cApp : public CWinApp

{:cApp();

// Overrides:BOOL InitInstance();

// Implementation_MESSAGE_MAP()

};

extern Cp2cApp theApp;

Заголовочный файл диалогового окна p2cDlg.h

/ p2cDlg.h : header file

//

#pragma once

// Cp2cDlg dialogCp2cDlg : public CDialog

{

// Construction:cDlg(CWnd* pParent = NULL);// standard constructorCodeC[100];//Объявляем строковой массив из 100 элементов, для хранения исходного кода на С++.* pCodeP;//Указатель на массив CodeCCodeP[100];//Объявляем строковой массив из 100 элементов, для хранения исходного кода на Паскале.* pCodeC;//Указатель на массив CodeP

// Dialog Data{ IDD = IDD_P2C_DIALOG };:void DoDataExchange(CDataExchange* pDX);// DDX/DDV support

// Implementation:m_hIcon;

// Generated message map functionsBOOL OnInitDialog();_msg void OnPaint();_msg HCURSOR OnQueryDragIcon();_MESSAGE_MAP():fRead(UINT nID, CString* String);fWrite(UINT nID, CString* String);_msg void OnBnClickedButton1();fComment(CString* String);fvar(CString* String);fMain(CString* String);fWhile(CString* String);_msg void OnBnClickedButton2();

};

Исполняющий файл приложения p2c.cpp

// p2c.cpp : Defines the class behaviors for the application.

//

#include "stdafx.h"

#include "p2c.h"

#include "p2cDlg.h"

#ifdef _DEBUG

#define new DEBUG_NEW

#endif

// Cp2cApp_MESSAGE_MAP(Cp2cApp, CWinApp)_COMMAND(ID_HELP, &CWinApp::OnHelp)_MESSAGE_MAP()

// Cp2cApp constructioncApp::Cp2cApp()

{

// TODO: add construction code here,

// Place all significant initialization in InitInstance

}

// The one and only Cp2cApp objectcApp theApp;

// Cp2cApp initializationCp2cApp::InitInstance()

{

// InitCommonControlsEx() is required on Windows XP if an application

// manifest specifies use of ComCtl32.dll version 6 or later to enable

// visual styles. Otherwise, any window creation will fail.InitCtrls;.dwSize = sizeof(InitCtrls);

// Set this to include all the common control classes you want to use

// in your application..dwICC = ICC_WIN95_CLASSES;(&InitCtrls);::InitInstance();();

// Standard initialization

// If you are not using these features and wish to reduce the size

// of your final executable, you should remove from the following

// the specific initialization routines you do not need

// Change the registry key under which our settings are stored

// TODO: You should modify this string to be something appropriate

// such as the name of your company or organization(_T("Local AppWizard-Generated Applications"));cDlg dlg;_pMainWnd = &dlg;_PTR nResponse = dlg.DoModal();

/*if (nResponse == IDOK)

{

// TODO: Place code here to handle when the dialog is

// dismissed with OK

}if (nResponse == IDCANCEL)

{

// TODO: Place code here to handle when the dialog is

// dismissed with Cancel

}

// Since the dialog has been closed, return FALSE so that we exit the

// application, rather than start the application's message pump.

*/return FALSE;

}

Исполняющий файл диалогового окна p2cDlg.cpp

// p2cDlg.cpp : implementation file

//

#include "stdafx.h"

#include "p2c.h"

#include "p2cDlg.h"

#ifdef _DEBUG

#define new DEBUG_NEW

#endif

// Cp2cDlg dialogcDlg::Cp2cDlg(CWnd* pParent /*=NULL*/)

: CDialog(Cp2cDlg::IDD, pParent)

{=&CodeP[0];//Создаем указатели на нулевые строки массивов.=&CodeC[0];(int i=0; i<100; i++)//Инициализируем элементы строковых массивов пустыми значениями.

{[i]="";[i]="";

}_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);

}Cp2cDlg::DoDataExchange(CDataExchange* pDX)

{::DoDataExchange(pDX);

}_MESSAGE_MAP(Cp2cDlg, CDialog)_WM_PAINT()_WM_QUERYDRAGICON()

//}}AFX_MSG_MAP_BN_CLICKED(IDC_BUTTON1, &Cp2cDlg::OnBnClickedButton1)_BN_CLICKED(IDC_BUTTON2, &Cp2cDlg::OnBnClickedButton2)_MESSAGE_MAP()

// Cp2cDlg message handlersCp2cDlg::OnInitDialog()

{::OnInitDialog();(IDC_EDIT1,pCodeP);//Первый аргумент - элемент диалога,

//в который будет выводиться текст, второй - указатель на массив строк.

// Set the icon for this dialog. The framework does this automatically

// when the application's main window is not a dialog(m_hIcon, TRUE);// Set big icon(m_hIcon, FALSE);// Set small icon

// TODO: Add extra initialization hereTRUE; // return TRUE unless you set the focus to a control

}

// If you add a minimize button to your dialog, you will need the code below

// to draw the icon. For MFC applications using the document/view model,

// this is automatically done for you by the framework.Cp2cDlg::OnPaint()

{(IsIconic())

{dc(this); // device context for painting(WM_ICONERASEBKGND, reinterpret_cast(dc.GetSafeHdc()), 0);

// Center icon in client rectanglecxIcon = GetSystemMetrics(SM_CXICON);cyIcon = GetSystemMetrics(SM_CYICON);rect;(&rect);x = (rect.Width() - cxIcon + 1) / 2;y = (rect.Height() - cyIcon + 1) / 2;

// Draw the icon.DrawIcon(x, y, m_hIcon);

}

{::OnPaint();

}

}

// The system calls this function to obtain the cursor to display while the user drags

// the minimized window.Cp2cDlg::OnQueryDragIcon()

{static_cast(m_hIcon);

}Cp2cDlg::OnBnClickedButton1()//Обработчик нажатия на кнопку.

{ int i=0;//Объявляем и инициализируем счетчик.(CodeP[i]!="")//Пока элемент массива не пустой

{[i]=CodeP[i];//Присваиваем строки* pTemp=&CodeC[i];//Создаем временный указатель на текущую строку.(pTemp);//Запускаем функции, передавая в кач-ве аргумента указатель на текущую строку.(pTemp);(pTemp);(pTemp);++;

}(IDC_EDIT2,pCodeC);//Вызываем функцию вывода результата и записи его в файл

}Cp2cDlg::fRead(UINT nID, CString* String)//Функция производит чтение строк из файла.

//Она же построчно заносит содержимое файла в строковый массив.

{szOut=""; //Создаем пустую строку, для вывода результата.Inputfile; //Создаем объект для файла.FileExc; //Объект исключений для файлаnOpenFlags; //Флаг открытияs; //Временная строка= CFile::modeRead;

//Если файл не открывается(!Inputfile.Open("CodePas.txt", nOpenFlags, &FileExc))

{.ReportError();//Выводим стандартное сообщение об ошибке;

}

//Пока возможно чтение строки...i=0;(Inputfile.ReadString(s))

{[i]=s;//Присваиваем строку из файла элементу строкового массива..Append(String[i]);//Добавляем текущую строку в строку результата..AppendChar('\r');//