This maybe a silly question but I'm stuck on this.
I'm doing an assignment on Compiler. I have to match a character literal. It's defined as any single character enclosed with ' ', with the exception of '\t','\n','\a' etc. In my lex file, I have written a pattern to match it. When the pattern matches the input, it stores it in yytext. Now yytext in a char pointer. It catches the value as '\t'. (4 individual chars). But I have save this character's ascii value in my Symbol table. I'm struggling with this.
I have this following char pointer.
char *yytext = new char[5];
*(yytext + 0) = '\'';
*(yytext + 1) = '\\';
*(yytext + 2) = 't';
*(yytext + 3) = '\'';
*(yytext + 4) = '\0';
cout << yytext << endl; // prints '\t'
Now what I want to do is get the '\t' ascii character in a single char. Something like:
char ch = '\t';
How can I do this? I might be able to do this by a brute-force approach, but is there any simple and straightforward way to achieve this?
But how do I parse it from the char pointer in an easy way ?
Use map with key being the string and the value being corresponding char:
#include <iostream>
#include <string>
#include <unordered_map>
int main()
{
std::unordered_map<std::string, char> convert = { {"'\t'", '\t'},{ "'\n'", '\n' },{ "'\r'", '\r' } };
const char *ch1 = "'\t'";
const char *ch2 = "'\n'";
std::cout << 1 << convert[ch1] << 2 << convert[ch2] << 3 << std::endl;
return 0;
}
Working demo: https://ideone.com/rsSKXL
1 2
3