编写词法分析器:词法分析器找不到"

Writing a lexer : lexer doesnt find "

本文关键字:词法分析器 找不到      更新时间:2023-10-16

我正在编写一种小型编程语言,该语言只有一个关键字为 write。我没有做解析器,而是勒克斯。它可以正常工作直到到达"代币。

main.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

我该怎么办?有什么想法吗?

我认为应该是 skipws而不是 noskipws,因为当它遇到"写"answers" hello"之间的空间时,您不会处理案例;具体来说,您不清除tok,因此它仍然认为令牌是一个空格。