词法分析器项目 - 矢量未正确输出

Lexical Analyzer Project - Vector not outputting correctly

本文关键字:输出 项目 词法分析器      更新时间:2023-10-16

我有以下代码,它是一个更大项目的一部分。这段代码应该做的是逐行逐行查找"令牌"。我在此代码中查找的令牌是 ID。它被定义为一个字母,后跟零个或多个数字或字母。

当检测到一个字母时,它会进入内部循环并循环访问接下来的几个字符,将每个字符或字母添加到 idstring 中,直到它找到 ID 字符的结尾(在代码中定义(,然后将该 idstring 添加到向量中。在行尾,它应该输出向量的每个元素。我没有得到我需要的输出。我希望这些信息足以理解代码中发生的事情。如果有人能帮我解决这个问题,我会非常充实。谢谢!

我需要的输出:

ab:ab

我得到的: a : a

#include <iostream>
#include <regex>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> id;
std::regex idstart("[a-zA-Z]");
std::regex endID("[^a-z]|[^A-Z]|[^0-9]");
std::string line = "ab ab";
//Loops character by character through the line
//Adding each recognized token to the appropriate vector
for ( int i = 0; i<line.length(); i++ )
  {
    std::string tempstring(1,line[i]);
    //Character is letter
    if ( std::regex_match(tempstring,idstart) )
      {
    std::string tempIDString = tempstring;
    int lineInc = 0;
    for ( int j = i + 1; j<line.length(); j++)
      {
        std::string tempstring2(1,line[j]);
        //Checks next character for end of potential ID
        if ( std::regex_match(tempstring2,endID) )
          {
        i+=lineInc+1;
        break;
          }
        else
          {
        tempIDString+=tempstring2;
        lineInc++;
          }
      }
    id.push_back(tempIDString);
      }       
  }
 std::cout << id.at(0) << " : " << id[1] << std::endl;
 return 0;
}

这个问题已经 2.5 岁了,现在你看到它可能会笑。在查找匹配的第二个字符时,您break;内部for,因此您永远不会将tempstring2分配给tempstring1

但是,让我们忘记该代码。这里没有好的设计。

你有一个使用std::regex的好主意,但你不知道它是如何工作的。

因此,让我们看一下正确的实现:

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <regex>
// Our test data (raw string). So, containing also n and so on
std::string testData(
R"#( :-)  IDcorrect1 _wrongID I2DCorrect
    3FALSE lowercasecorrect Underscore_not_allowed
i3DCorrect,i4 :-)
}
)#");
std::regex re("(\b[a-zA-Z][a-zA-Z0-9]*\b)");
int main(void)
{
    // Define the variable id as vector of string and use the range constructor to read the test data and tokenize it
    std::vector<std::string> id{ std::sregex_token_iterator(testData.begin(), testData.end(), re, 1), std::sregex_token_iterator() };
    // For debug output. Print complete vector to std::cout
    std::copy(id.begin(), id.end(), std::ostream_iterator<std::string>(std::cout, "n"));
    return 0;
}

这将完成变量定义中的所有工作,并调用范围构造函数。所以,典型的单行本。

希望有人能从这段代码中学习。 .