Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <regex>
- #include <fstream>
- std::string IntToString(int a) {
- std::string result;
- int number = abs(a);
- while (number) {
- result += (number % 10) + 48;
- number /= 10;
- }
- if (a < 0) result += '-';
- std::reverse(result.begin(), result.end());
- return result;
- }
- /////////////////////////////ЛЕКСИЧЕСКИЙ АНАЛИЗ////////////////////////////////
- //список лексем
- struct node {
- std::string id;
- int n;
- node *next;
- };
- node *head;
- node *tail;
- void addToList (std::string value, int i) {
- if (head == NULL) {
- head = new node();
- head->n = i;
- head->id = value;
- head->next = NULL;
- tail = head;
- }
- else {
- tail->next = new node();
- tail = tail->next;
- tail->n = i;
- tail->id = value;
- tail->next = NULL;
- }
- }
- int searchInList (std::string value) {
- //bool b;
- node *point = head;
- while (point != NULL) {
- if (value == point->id) {
- return point->n;
- }
- point = point->next;
- };
- return 0;
- }
- void removeList () {
- node *point = head;
- node *pBuf;
- while (point != NULL) {
- pBuf = point->next;
- delete point;
- point = pBuf;
- }
- }
- void searchLexemes(std::string& input, int& i, int type, std::ofstream& fout)
- {
- std::string strBuf;
- switch (type) {
- case 1: { //переменные
- strBuf = "[a-z][a-z0-9]*";
- break;
- }
- case 2: { //числа с плавающей точкой
- strBuf = "\\d(\\.?\\d+)?E[+-]\\d+";
- break;
- }
- case 3: { //числа с фиксированной точкой
- strBuf = "[0-9]+\\.[0-9]+";
- break;
- }
- case 4: { //целые числа
- strBuf = "[0-9]+";
- break;
- }
- }
- std::cout << "Start search" << std::endl;
- std::smatch m;
- std::regex rExp(strBuf);
- strBuf = input;
- input = "";
- bool foundAny = false;
- int i2;
- while (std::regex_search (strBuf, m, rExp)) {
- auto x = m.str();
- std::cout << "Found " << x << std::endl;
- i2 = searchInList(x);
- std::cout << "i2 = " << i2 << std::endl;
- if (i2 == 0) { //новая лексема
- i2 = i;
- addToList(x, i);
- i++;
- }
- input += m.prefix();
- input += "i" + IntToString(i2);
- strBuf = m.suffix();
- foundAny = true;
- }
- foundAny ? input += m.suffix() : input = strBuf;
- }
- void main() {
- std::string input;
- input = "fgs1=(b+a*5.01E+10)+a*10+(c*10.5)*51E-10";
- std::ofstream fout;
- fout.open("OUTPUT.TXT");
- int intBuf;
- int i = 1; //номер последней лексеммы
- std::cout << input << std::endl;
- searchLexemes(input, i, 1, fout);
- searchLexemes(input, i, 2, fout);
- searchLexemes(input, i, 3, fout);
- searchLexemes(input, i, 4, fout);
- std::cout << input << std::endl;
- //ожидаемый результат - "i1=(i2+i3*i5)+i3*i8+(i4*i7)*i6"
- removeList();
- system ("pause");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement