-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLaxical_analyzer.cpp
122 lines (100 loc) · 3.09 KB
/
Laxical_analyzer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
#include <cstdlib>
using namespace std;
// Function to check if a given string is a keyword
bool isKeyword(string str)
{
string keywords[4] = {"if", "else", "for", "while"};
for (int i = 0; i < 4; i++)
if (str.compare(keywords[i]) == 0)
return true;
return false;
}
// Function to detect syntax
void syntaxDetect(string input)
{
// Initializing variables
int i = 0;
char currentChar = input[0];
while (i < input.length())
{
// Check for identifier or keyword
if (isalpha(currentChar) || currentChar == '_')
{
string identifier = "";
identifier += currentChar;
i++;
while (isalpha(currentChar = input[i]) || isdigit(currentChar) || currentChar == '_')
{
identifier += currentChar;
i++;
}
if (isKeyword(identifier))
cout << identifier << " is a keyword." << endl;
else
cout << identifier << " is an identifier." << endl;
}
// Check for numerical constant
else if (isdigit(currentChar))
{
string num = "";
num += currentChar;
i++;
while (isdigit(currentChar = input[i]))
{
num += currentChar;
i++;
}
cout << num << " is a numerical constant." << endl;
}
// Check for operators
else if (currentChar == '+' || currentChar == '-' || currentChar == '*' || currentChar == '/' || currentChar == '%' || currentChar == '=' || currentChar == '>' || currentChar == '<' || currentChar == '!' || currentChar == '&' || currentChar == '|' || currentChar == '^' || currentChar == '~' || currentChar == '?')
{
string op = "";
op += currentChar;
i++;
if (currentChar == '=')
{
if (input[i] == '=')
{
op += currentChar;
i++;
}
}
cout << op << " is an operator." << endl;
}
// Check for punctuation
else if (currentChar == ',' || currentChar == ';' || currentChar == ':' || currentChar == '(' || currentChar == ')' || currentChar == '{' || currentChar == '}' || currentChar == '[' || currentChar == ']')
{
string punct = "";
punct += currentChar;
i++;
cout << punct << " is a punctuation symbol." << endl;
}
// Ignore spaces
else if (currentChar == ' ')
i++;
// Invalid character
else
{
cout << "Invalid character: " << currentChar << endl;
i++;
}
// Get the next character
currentChar = input[i];
}
}
// Main function
int main()
{
// Getting input from user
string input;
cout << "Enter a statement: ";
getline(cin, input);
// Detecting syntax
syntaxDetect(input);
return 0;
}