【问题标题】:Writing a lexer : lexer doesnt find "编写词法分析器:词法分析器找不到“
【发布时间】:2017-06-28 09:36:00
【问题描述】:

我正在编写一种只有一个关键字 write 的小型编程语言。我没有做过解析器,而是词法分析器。在到达 " 令牌之前它工作正常。

ma​​in.cpp:

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <vector>
using namespace std;

int main(int argc, char* argv[2])
{
    char text;
    string tok = "";
    string str = "";
    vector <string> tokens;

    fstream inFile(argv[1]);

    while (inFile >> noskipws >> text)
    {
        tok += text;

        if (tok == "write")
        {
            tokens.push_back(tok);
            tok = "";
        }
        else if(tok == "\"")
        {
            str += text;
            tokens.push_back("String:"+str);
            str = "";
            tok = "";
            tok += text;
            }

        for (auto const& c : tokens)
            std::cout << c << ' ';
    }

    return 0;
}

test.txt:

write "hello"

输出是:

write write write write write write write ...

而不是,

String:hello

我能做什么?有什么想法吗?

【问题讨论】:

  • 调试器是解决此类问题的正确工具。 询问 Stack Overflow 之前,您应该逐行浏览您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 edit 您的问题包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
  • 调试器没有报错
  • 当您逐行浏览代码时,变量值是什么? string tokens[]; 看起来也错了,它还能编译吗?
  • 删除了还是什么都没有
  • 再一次,当您单步执行时,变量值是什么?

标签: c++ lexer


【解决方案1】:

我觉得应该是skipws而不是noskipws,因为遇到“write”和“hello”之间的空格你不处理;特别是你没有清除tok,所以下一个循环它仍然认为令牌是一个空格。

【讨论】:

  • 非常非常非常感谢
  • @GameplayerXd 没问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-15
  • 2012-05-17
  • 1970-01-01
  • 1970-01-01
  • 2022-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多