C++ 中的词法分析器
词法分析器是一种计算机程序,可将文本流分解为标记并标记它们的类型。它将输入作为一个任意长的字符序列,称为输入字符串,并将输出作为一个或多个字符序列,称为标记序列。
输出可能是令牌序列或仅足以唯一识别它们的信息。
此外,词法分析器通常实现为两个独立的程序:一个从输入流中读取字符,另一个为遇到的每个单词输出标记。
词法分析器主要用于识别文本文件中的错误,例如拼写错误或语法错误。它还用于检测自然语言中的某些模式,如果它们在现实生活中出现,可能会被认为是有害或危险的。
C++ 中词法分析器中标记的概念
令牌是程序中最小和最不可分割的组件。每种语言都有各种类型的标记。
标识符是用户分配给程序多个部分的名称,例如特征和参数。它们之所以这样称呼,是因为它们识别
了一个特定的内存地址。
然后是关键字,是语言用来执行各种功能的单词的集合。在 C++ 中,这些包括 cout
、cin
、if
、else
、for
、break
、continue
等等。
标点符号用于创建表达式和语句,它们仅在与语句中的能指或关键字结合时才有用。
C++ 中词法分析器的用途
词法分析器执行以下任务。
在 C++ 中使用词法分析器的步骤
让我们讨论在 C++ 中使用词法分析器的步骤。
C++ 中的词法分析器示例:
#include <string>
#include <bits/stdc++.h>
using namespace std;
vector<string> demo ={"auto","break","case","char","const","continue","default",
"do","double","else","enum","extern","float","for","goto",
"if","int","signed",
"sizeof","static","struct","switch","typedef","union",
"unsigned","void","volatile","while"};
vector<string> hello ={"-","*","=","+","/"};
vector<string> ten ={"67","87","5","12","90"};
vector<string> parenthesis = {"(",")"};
vector<string> brackets = {"[","]"};
void printout(string q){
if(find(demo.begin(), demo.end(), q) != demo.end())
cout<<q<<" \t keyword\n";
else if(find(hello.begin(), hello.end(), q) != hello.end())
cout<<q<<" \t operator\n";
else if(find(ten.begin(), ten.end(), q) != ten.end())
cout<<q<<" \t number\n";
else if(find(parenthesis.begin(), parenthesis.end(), q) != parenthesis.end())
cout<<q<<" \t paranthesis\n";
else if(find(brackets.begin(), brackets.end(), q) != brackets.end())
cout<<q<<" \t seperator\n";
}
int main(){
string line;
vector<string> sample;
while(getline(cin, line, ' ')){
sample.push_back(line);
}
for(auto q : sample)
printout(q);
return 0;
}
相关文章
Arduino 复位
发布时间:2024/03/13 浏览次数:315 分类:C++
-
可以通过使用复位按钮,Softwarereset 库和 Adafruit SleepyDog 库来复位 Arduino。
Arduino 的字符转换为整型
发布时间:2024/03/13 浏览次数:181 分类:C++
-
可以使用简单的方法 toInt()函数和 Serial.parseInt()函数将 char 转换为 int。
Arduino 串口打印多个变量
发布时间:2024/03/13 浏览次数:381 分类:C++
-
可以使用 Serial.print()和 Serial.println()函数在串口监视器上显示变量值。