Alright, so I'm writing a file for the lexical analyzer (lex). It will be used to check C code (collecting the identifiers and storing those names along with the line numbers the identifier was found on). I'm not used to 'C' so I'm having some difficulty.
I am using a function (insertId()) to actually add to the c-string array.
%{
#include <stdio.h>
#include <string.h>
const char* id[1000];
void insertId(char*, int);
int i = 0;
int newLineCnt = 1;
%}
%%
[a-zA-Z][a-zA-Z0-9_]+ {
id = yytext;
// printf("The word found was: %s and 'i' is: %d\n", id, i);
insertId(yytext, newLineCnt);
}
"\n" newLineCnt++;
[a-z] printf("Lowercase word\n");
[A-Z] printf("Uppercase word\n");
[0-9] printf("Integer\n");
";" printf("Semicolon");
"(" printf("Open parentheses\n");
")" printf("Close parentheses");
%%
void insertId(char* str, int nLine)
{
char num[2];
sprintf ( num, "%d", nLine);
static char string[100];
int iter;
for(iter = 0; iter < i+1; iter++)
{
if ( strcmp(str, id[iter]) == 0 )
{
strcat( string, ", " );
strcat( string, num );
strcat ( id[iter], string );
//printf("The word found was: %s\n", id[iter]);
return;
}
}
i++;
// printf("That string was: %s\n", str);
strcpy ( string, str);
strcat ( string, ": ");
sprintf ( num, "%d", nLine);
strcat (string, num);
// sprintf ( num, "%d", nLine);
// strcat (string, num);
id = string;
//printf("The word found was: %s on line %d\n", id[i-1], nLine);
}
Sample input:
Output should look like this below:
argc: 4, 5, 11, 13, 16, 18
argv: 4, 6, 11, 14, 17
exit: 23
fputs: 17
i: 8, 16, 17, 18
main: 4
nflg: 8, 10, 12, 21
putchar: 19, 22
sccsid: 1
stdout: 17