Перейти из форума на сайт.

НовостиФайловые архивы
ПоискАктивные темыТоп лист
ПравилаКто в on-line?
Вход Забыли пароль? Первый раз на этом сайте? Регистрация
Компьютерный форум Ru.Board » Компьютеры » Прикладное программирование » Задачи по C/С++

Модерирует : ShIvADeSt

 Версия для печати • ПодписатьсяДобавить в закладки
На первую страницук этому сообщениюк последнему сообщению

Открыть новую тему     Написать ответ в эту тему

Rollond

Newbie
Редактировать | Профиль | Сообщение | Цитировать | Сообщить модератору

примерный образец задачи похожей есть, но не могу разобраться где надо менять листинг.
1.1.    оператор присваивания « = »
1.2.    логическое сложение « ++ »
1.3.    оператор цикла, построенный в соответствии с предложенным синтаксисом конструкции: DO <имя параметра цикла>=m,n BEGIN <тело цикла> END
1.4.    оператор вывода переменных WRITE (<список переменных>)
2.    программа языка имеет структуру:
2.1.    VAR <список переменных через запятую> : INTEGER
2.2.    BEGIN <операторы программы> END
Текст программы:
#include <ctype.h>
#include <strng.h>
#include <conio.h>
#include <fstream.h>
#include <stdlib.h>
#include <list.h>
#include <clstypes.h>
 
const char
    *cpFileInName     = "!prg-in.txt", //файл с текстом программы
    *cpFileLexOut    = "!prg-lx.txt", //программа, разложенная на лексемы
    *cpFileIdOut    = "!prg-id.txt"; //список найденных лексем
const char
    *cpSystemLexems[] = {
        "var",
        "begin",
        "end",
        "read",
        "write",
        "integer",
        "for",
        "to",
        "if",
        "then",
        "do",
        NULL
    },
    *cpOperators[] = {
        "+",
        "-",
        "*",
        "/",
        "=",
        "(",
        ")",
        ",",
        ":",
        ";",
        "++",
        ">=",
        "<=",
        NULL
    };
 
enum     eLexemType {
    iUnknownLexem = __firstUserClass,
    iSystemLexem,
    iOperatorLexem,
    iConstantLexem,
    iVariableLexem
};
 
class Lexem: public String {
 public:
 Lexem(const String& astrName): String(astrName) {}
 virtual classType isA() const = 0;
 virtual char *nameOf() const = 0;
 virtual int isEqual(const Object& aoObj) const {
  return (aoObj.isA() == isA() && String::isEqual(aoObj));
 }
 virtual void printOn(ostream& aoStream) const {
  String::printOn(aoStream);
  if (aoStream.flags() & ios::binary) aoStream<<hashValue()<<isA();
   else aoStream<<':'<<hashValue()<<':'<<nameOf();
 }
};
 
class SystemLexem: public Lexem {
 public:
 SystemLexem(const String& astrName):Lexem(astrName) {}
 virtual classType isA() const {return iSystemLexem;}
 virtual char *nameOf() const {return "SystemLexem";}
};
 
class OperatorLexem: public Lexem {
 public:
 OperatorLexem(const String& astrName):Lexem(astrName) {}
 virtual classType isA() const {return iOperatorLexem;}
 virtual char *nameOf() const {return "OperatorLexem";}
};
 
class ConstantLexem: public Lexem {
 public:
 ConstantLexem(const String& astrName):Lexem(astrName) {}
 virtual classType isA() const {return iConstantLexem;}
 virtual char *nameOf() const {return "ConstantLexem";}
};
 
class VariableLexem: public Lexem {
 public:
 VariableLexem(const String& astrName):Lexem(astrName) {}
 virtual classType isA() const {return iVariableLexem;}
 virtual char *nameOf() const {return "VariableLexem";}
};
 
void error(char *acpDescription) {
 cerr<<acpDescription<<endl;
 exit(-1);
}
 
void addSystemLexems(List& aList, char **acpSystemLexems) {
 char **p = acpSystemLexems;
 while(*p) { aList.add(* new SystemLexem(*p)); p++; }
}
 
void addOperators(List& aList, char **acpOperators) {
 char **p = acpOperators;
 while(*p) { aList.add(* new OperatorLexem(*p)); p++; }
}
 
String loadFile(char *acpFileName) {
 char acBuf[32000];
 ifstream oStream(acpFileName);
 if (oStream) {
  oStream.read(acBuf, sizeof(acBuf)-1);
  if (oStream || oStream.eof()) {
   acBuf[oStream.gcount()]=0;
   return String(acBuf);
  }
 }
 oStream.close();
 return NULL;
}
 
int saveFile(char * acpFileName, List& aoList) {
 ofstream oStream(acpFileName);
 if (oStream) {
  oStream<<aoList;
  if (oStream.good()) return oStream.tellp();
 }
 oStream.close();
 return NULL;
}
 
void lexAnalyze(List& aoFoundList, List& aoLexemList, String& astrText) {
 const char *cpText = astrText;
 char *cpStart = (char*)cpText;
 String strWord;
 char c = *cpStart;
 while(c) {
  char *cpEnd = cpStart;
  if (isgraph(c)) {
   if (islower(c)) {
    //Find end of the lexem
    while(*cpEnd && (islower(*cpEnd) || isdigit(*cpEnd))) cpEnd++;
    c = *cpEnd; *cpEnd = 0;  strWord = cpStart; *cpEnd = c;
    //Try to find in System Lexem
    Object& oFindSysLexem = aoLexemList.findMember(SystemLexem(strWord));
    //If not found - then it is a Variable
    if (oFindSysLexem == NOOBJECT) {
     //Try to find in a Variable Lexems
     Object& oFindVarLexem = aoLexemList.findMember(VariableLexem(strWord));
     //If not found - then it is a new Variable
     if (oFindVarLexem == NOOBJECT)
      aoLexemList.add(*new VariableLexem(strWord));
     aoFoundList.add(*new VariableLexem(strWord));
    } else aoFoundList.add(*new SystemLexem(strWord));
   } else
   if (isdigit(c)) {
    while(*cpEnd && isdigit(*cpEnd)) cpEnd++;
    c = *cpEnd; *cpEnd = 0; strWord = cpStart; *cpEnd = c;
    Object& oFindConstLexem = aoLexemList.findMember(ConstantLexem(strWord));
    if (oFindConstLexem == NOOBJECT)
     aoLexemList.add(*new ConstantLexem(strWord));
    aoFoundList.add(*new ConstantLexem(strWord));
   } else
   if (!(isdigit(c) || islower(c))) {
    while(*cpEnd && !(isdigit(*cpEnd) || islower(*cpEnd))) cpEnd++;
    c = *cpEnd; *cpEnd = 0;  strWord = cpStart; *cpEnd = c;
    Object& oFindOpLexem = aoLexemList.findMember(OperatorLexem(strWord));
    if (oFindOpLexem != NOOBJECT)
     aoFoundList.add(*new OperatorLexem(strWord));
   }
  }
  if (cpStart==cpEnd) cpEnd++;
  cpStart = cpEnd;
  c=*cpStart;
 }
}
 
void main() {
 clrscr();
 String strText = loadFile((char*)cpFileInName);
 const char *pText = strText;
 
 if (!*pText) error("reading source file");
 strlwr((char*)pText);
 
 List oLexemList;
 List oFoundList;
 
 addSystemLexems(oLexemList, (char**)cpSystemLexems);
 addOperators(oLexemList, (char**)cpOperators);
 
 lexAnalyze(oFoundList, oLexemList, strText);
 
 if (!saveFile((char*)cpFileIdOut, oLexemList)) error("writing id file");
 if (!saveFile((char*)cpFileLexOut, oFoundList)) error("writing lex file");
}

Всего записей: 3 | Зарегистр. 13-03-2008 | Отправлено: 10:57 13-03-2008 | Исправлено: Rollond, 11:07 13-03-2008
Открыть новую тему     Написать ответ в эту тему

На первую страницук этому сообщениюк последнему сообщению

Компьютерный форум Ru.Board » Компьютеры » Прикладное программирование » Задачи по C/С++


Реклама на форуме Ru.Board.

Powered by Ikonboard "v2.1.7b" © 2000 Ikonboard.com
Modified by Ru.B0ard
© Ru.B0ard 2000-2024

BitCoin: 1NGG1chHtUvrtEqjeerQCKDMUi6S6CG4iC

Рейтинг.ru