const char *lex1 = "\'a\'"; // prints 'a'
const char *lex2 = "\'\\t\'"; // prints '\t'
const char *lex3 = "\'0\'"; // prints '0'
How would I convert from a char *
to the representative char
? For the above example, the conversion is as follows:
char lex1_converted = 'a';
char lex2_converted = '\t';
char lex3_converted = '0';
I am currently thinking of chains of if-else
blocks, but there might be a better approach.
This is a homework problem related to lexical analysis with flex
. Please provide the minimum hint required to comprehend the solution. Thanks!
Edit: Looks like I misinterpreted the tokenized strings in my first post :)
CodePudding user response:
const char* lex1="your sample text";
char lex1_converted=*lex1;
this code will convert the first char of your lex1 , and if you want to convert others you had to do this
char lex1_converted=*(lex1 your_disire_index);
//example
char lex1_converted=*(lex1 1);
and also the other way is doing this
char lex1_converted=lex1[your_desire_index];
CodePudding user response:
Please provide the minimum hint required to comprehend the solution.
A key attribute of the conversion is to detect that the source string may lack the expected format.
Below some untested sample code to get OP started.
Sorry, did not see "homework problem related to lexical analysis with flex" until late.
Non-flex, C only approach:
Pseudo code
// Return 0-255 on success
// Else return -1.
int swamp_convert(s)
Find string length
If length too small or string missing the two '
return fail
if s[1] char is not \
if length is 3, return middle char
return fail
if length is 4 & character after \ is a common escaped character, (search a string)
return corresponding value (table lookup)
Maybe consider octal, hexadecimal, other escaped forms
else return fail
// Return 0-255 on success
// Else return -1.
int swamp_convert(const char *s) {
size_t len = strlen(s);
if (len < 3 || s[0] != '\'' || s[len - 1] != '\'') {
return -1;
}
if (s[1] != '\\') {
return (len == 3) ? s[1] : -1;
}
// Common escaped single charters
const char *escape_chars = "abtnvfr\\\'\"";
const char *e = strchr(escape_chars, s[2]);
if (t && len == 4) {
return "\a\b\t\n\v\f\r\\\'\""[e - escape_chars];
}
// Additional code to handle \0-7, \x, \X, maybe \e ...
return -1;
}