Greetings. sem is a pointer to semantic which is a struct type variabl.
I pass the sem into function yylex so i can fill the semantic.i and semantic.s(s points to an array).
The problem is that when sem->i = a; is used inside yylex function, sem->s stops showing to the array. Can anyone solve this? thank you.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <iostream>
usingnamespace std;
union SEMANTIC_INFO
{
int i;
char *s;
}semantic;
int yylex(FILE *fpointer, SEMANTIC_INFO *sem)
{
char c;
int i=0;
int j=0;
int a=0;
c = fgetc (fpointer);
while(c != EOF)
{
if(isalpha(c))
{
do
{
sem->s[i] = c; //<---there is the error when i run it
c = fgetc(fpointer);
i++;
}while(isalnum(c));
return 1;
}
elseif(isdigit(c))
{
char arithmoi[20];
do
{
arithmoi[j] = c;
j++;
c = fgetc(fpointer);
}while(isdigit(c));
a = atoi(arithmoi);
sem->i = a; //->>when i use this and return the next time yylex will be called and
// the next word starts with a letter the error occurs
return 2;
}
else
{
do
{
c=fgetc(fpointer);
}while(isalnum(c) == false && c != EOF);
}
}
cout << "end of file" << endl;
return 0;
}
int main()
{
char str[20];
int i,k;
char c[20];
int counter1 = 0;
int counter2 = 0;
for(i=0; i < 20; i++)
{
c[i] = ' ';
}
SEMANTIC_INFO *sema = &semantic;
semantic.s = c;
cout << "dwste to onoma tou arxeio (mazi me to .txt)" << endl;
scanf ("%s", str);
FILE *pFile;
pFile = fopen (str , "r");
do
{
k = yylex( pFile, sema);
if(k == 1)
{
counter1++;
cout << "it's type is alfanumeric and it's: ";
for(i=0; i<20; i++)
{
cout << semantic.s[i] ;
}
cout <<endl;
for(i=0; i < 20; i++)
{
c[i] = ' ';
}
}
elseif(k==2)
{
counter2++;
cout << "it's type is digit and it's: "<< semantic.i << endl;
}
}while(k != 0);
cout<<"the alfanumeric are : " << counter1 << endl;
cout<<"the digits are: " << counter2 << endl;
fclose (pFile);
system("pause");
return 0;
}
SEMANTIC_INFO *sema = &semantic;
//semantic.s = c; //Move this from here
cout << "dwste to onoma tou arxeio (mazi me to .txt)" << endl;
scanf ("%s", str);
FILE *pFile;
pFile = fopen (str , "r");
do
{
semantic.s = c; //and put it here
k = yylex( pFile, sema);
if(k == 1)
{
counter1++;
But you need to read up on unions.
A union does not have seperate members like a struct.
In a union all the members share the same space.
Once you understand that - you will find out whythis bit of
code below taken from the from the yylex function was causing a crash (and why the solution I suggested above would avoid the crash )
1 2 3 4 5 6 7 8
j++;
c = fgetc(fpointer);
}while(isdigit(c));
a = atoi(arithmoi);
sem->i = a; //->>when i use this and return the next time yylex will be called and
// the next word starts with a letter the error occurs
return 2;
In reality most people would have used a struct rather than a union for this;