2 sean1993519 sean1993519 于 2013.11.07 15:25 提问

求助如何一行一行读取文件

学校要求编写词法分析器,然后代码如下,不知道为什么只能读第一行,后面的读不了。希望高手帮助一下
//#include "stdafx.h"
#include
#include
#include
using namespace std;
ofstream fout;//输出文件

int judge(string str,int &lt,int i,int &ch)
{
int rt=lt;int wh;
string doc[6]={"if","else","while","return","void","int"};
string docc[6]={"IF","ELSE","WHILE","RETURN","VOID","INT"};

if(str[lt]==' ')
{
lt++;
rt++;
wh=1;
}

/*if(*c=='\n ')
{
i++;
c=&str[0];
d=&str[0];
}*/

//运算符
if(str[lt]=='+')
{
fout<<""<<endl;
lt++;
rt++;
wh=1;
}

if(str[lt]=='-')
{
fout<<""<<endl;
lt++;
rt++;
wh=1;
}

if(str[lt]=='*')
{
fout<<""<<endl;
lt++;
rt++;
wh=1;
}

if(str[lt]=='/')
{
fout<<""<<endl;
lt++;
rt++;
wh=1;
}

if(str[lt]=='=')
{
fout<<""<<endl;
lt++;
rt++;
wh=1;
}

if(str[lt]=='<')
{
rt++;
if(str[rt]=='=')
{
fout<<""< rt++;
lt=rt;
wh=2;
}
else
{
fout"<<endl;
lt=rt;
wh=1;
}
}

if(str[lt]=='>')
{
rt++;
if(str[rt]=='=')
{
fout<<"=” />"< rt++;
lt=rt;
wh=2;
}
else
{
fout” />"<<endl;
lt=rt;
wh=1;
}
}

if(str[lt]=='!')
{
rt++;
if(str[rt]=='=')
{
fout<<""<<endl;
rt++;
lt=rt;
wh=2;
}
else
{
fout<<"wrong"<<endl;
lt=rt;
wh=1;
}
}

//界符
if(str[lt]==',')
{
fout<<""<<endl;
lt++;
rt++;
wh=1;
}

if(str[lt]==';')
{
fout<<""<<endl;
lt++;
rt++;
wh=1;
}

if(str[lt]=='(')
{
fout<<""<<endl;
lt++;
rt++;
wh=1;
}

if(str[lt]==')')
{
fout<<""<<endl;
lt++;
rt++;
wh=1;
}

if(str[lt]=='[')
{
fout<<""<<endl;
lt++;
rt++;
wh=1;
}

if(str[lt]==']')
{
fout<<""<<endl;
lt++;
rt++;
wh=1;
}

if(str[lt]=='{')
{
fout<<""<<endl;
lt++;
rt++;
wh=1;
}

if(str[lt]=='}')
{
fout<<""<<endl;
lt++;
rt++;
wh=1;
}

//标识符&关键字
if((str[lt]>='A'&&str[lt]<='Z')||(str[lt]>='a'&&str[lt]<='z'))
{
char mid[100];int t=1,k,q=0;
rt++;
mid[0]=str[lt];
for(t=1;(str[rt]>='A'&&str[rt]<='Z')||(str[rt]>='0'&&str[rt]<='9')||(str[rt]>='a'&&str[rt]<='z');t++)
{
mid[t]=str[rt];
rt++;
}
mid[t]='\0';
for(k=0;k {
if(mid==doc[k])
{
fout"< q=1;
}
}
if(q==0)
fout"<<endl;
wh=t;
}

if(str[lt]>='0'&&str[lt]<='9')
{
char mid[100];int t=1,k;
rt++;
mid[0]=str[lt];
while(str[rt]>='0'&&str[rt]<='9')
{
mid[t++]=str[rt];
rt++;
}
mid[t]='\0';
fout<<""<<endl;
wh=t;
}

ch=wh;
return 0;
}

int main()
{
ifstream fin;//输入文件

fin.open("in.txt");
fout.open("out.txt");
fout<<"<?xml version=\"1.0\"?>"< fout"<<endl;
string si;

if(fin)
{
int i=0,j=0,ch=0;

while (!fin.eof())
{
getline(fin,si);
j++;
int l=si.length();
while (i<l)
{
ch=1;
judge(si,i,j,ch);
i=i+ch;
}

}
fout<<""<<endl;
fin.close();
fout.close();
return 0;
}
}

Csdn user default icon
上传中...
上传图片
插入图片