写在前面
纯粹,为了记录.
以后某一天,回过头来看看.给大学留些痕迹hh.
PS:很多思路也都是学习前辈们的,如果能顺便帮到你,不客气!
内容
编译原理 实验1
编制一个程序,该程序的功能是能打开一个高级语言程序的源文件,扫描该源程序文件的字符,并识别该源程序文中的关键字和保留字,把识别的结果保存到一个新的文件中,格式是关键字或保留字(该关键字或保留字所在的行号)。
源代码
/*
#include <fstream>
ofstream //文件写操作 内存写入存储设备
ifstream //文件读操作,存储设备读区到内存中
fstream //读写操作,对打开的文件可进行读写操作
*/
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include <cstdio>
using namespace std;
void findKey(string str, int lineNum)
{
string key[32] = { "auto ", "double ", "int ", "struct ", "break ", "else ", "long ", "switch ",
"case ", "enum ", "register ", "typedef ", "char ", "extern ", "return ", "union ",
"const ", "float ", "short ", "unsigned ", "continue ", "for ", "signed ", "void ",
"default ", "goto ", "sizeof ", "volatile ", "do ", "if ", "while ", "static " };
for (int i = 0; i < 32; i++)
{
int begin = str.find(key[i], 0);
if (begin != string::npos)
{
printf("位置:(%d,%d),找到:%s\n", lineNum, begin, key[i].c_str());
char ss[256];
sprintf_s(ss, "位置:(%d,%d),找到:%s\n", lineNum, begin, key[i].c_str());
ofstream outfile; //输出流类
outfile.open("D:\\ProgramData\\vsFiles\\test_out.txt", ios::app); //以追加的方式打开文件
assert(outfile.is_open()); //若打开失败,则输出错误信息,并终止程序
outfile.write(ss, strlen(ss));
outfile.close();
}
}
}
int main()
{
ifstream infile; //文件读操作
string filePath = "D:\\ProgramData\\vsFiles\\test.c";
infile.open(filePath.data()); //将文件流对象与文件连接
assert(infile.is_open()); //若打开失败,则输出错误信息,并终止程序
string str;
int lineNum = 0;
while ( getline(infile, str) )
{
findKey(str, lineNum);
lineNum++;
}
infile.close();
return 0;
}
805

被折叠的 条评论
为什么被折叠?



