【问题标题】:Get ASCII value from yytext [closed]从 yytext 获取 ASCII 值 [关闭]
【发布时间】:2018-05-03 20:29:37
【问题描述】:

这可能是一个愚蠢的问题,但我被困在这个问题上。

我正在 Compiler 上做作业。我必须匹配一个字符文字。它被定义为用 ' ' 括起来的任何单个字符,但 '\t'、'\n'、'\a' 等除外。在我的 lex 文件中,我编写了一个模式来匹配它。当模式与输入匹配时,它将其存储在 yytext 中。现在 yytext 在一个 char 指针中。它将值捕获为 '\t'。 (4 个单独的字符)。但是我已经在我的符号表中保存了这个字符的 ascii 值。我正在为此苦苦挣扎。

我有以下 char 指针。

 char *yytext = new char[5];
 *(yytext + 0) = '\'';
 *(yytext + 1) = '\\';
 *(yytext + 2) = 't';
 *(yytext + 3) = '\'';
 *(yytext + 4) = '\0';

 cout << yytext << endl; // prints '\t'

现在我想做的是在单个字符中获取 '\t' ascii 字符。比如:

char ch = '\t';

我该怎么做?我也许可以通过蛮力方法做到这一点,但是有没有简单直接的方法来实现这一点?

【问题讨论】:

  • 类似:char ch = '\t'; 你就是这样做的。但我看不出其余代码与此有什么关系。
  • *(ch + 0) = '\'';可以替换成更简单易读的ch[0] = '\''
  • 可能是别的东西。像'\a' 或'\n'。我怎样才能提前知道这个 char 指针包含哪些字符?我只能使用这个 char 指针。
  • 您是在问如何访问数组中的第三个char

标签: c++ pointers compiler-construction flex-lexer char-pointer


【解决方案1】:

但是如何以简单的方式从 char 指针中解析它呢?

使用map,key为字符串,value为对应的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;
}

工作演示:https://ideone.com/rsSKXL

1   2
3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2013-12-15
    • 1970-01-01
    相关资源
    最近更新 更多