C++ 词法分析器项目-向量输出不正确

C++ 词法分析器项目-向量输出不正确,c++,C++,我有以下代码,这是一个更大的项目的一部分。这段代码要做的是逐行字符查找标记。我在这段代码中寻找的标记是一个ID,它被定义为一个字母后跟零个或多个数字或字母 当检测到一个字母时,它进入内部循环并循环通过接下来的几个字符,将每个字符或字母添加到ID字符串中,直到找到代码中定义的ID字符的结尾,然后将该ID字符串添加到向量中。在行尾,它应该输出向量的每个元素。我没有得到我需要的输出。我希望这是足够的信息来理解代码中发生了什么。如果有人能帮我解决这个问题,我会非常高兴。谢谢大家! 我需要的输出:ab:a

我有以下代码,这是一个更大的项目的一部分。这段代码要做的是逐行字符查找标记。我在这段代码中寻找的标记是一个ID,它被定义为一个字母后跟零个或多个数字或字母

当检测到一个字母时,它进入内部循环并循环通过接下来的几个字符,将每个字符或字母添加到ID字符串中,直到找到代码中定义的ID字符的结尾,然后将该ID字符串添加到向量中。在行尾,它应该输出向量的每个元素。我没有得到我需要的输出。我希望这是足够的信息来理解代码中发生了什么。如果有人能帮我解决这个问题,我会非常高兴。谢谢大家!

我需要的输出: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岁了,现在你看到它可能会笑。你打破;查找匹配的第二个字符时的内部值,因此永远不会将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;
}
这将通过调用范围构造函数完成变量定义中的所有工作。所以,一个典型的单班轮


希望有人能从这个代码中学习

是的,这是一个家庭作业项目。我们正在做一个词法分析器,我已经被这个愚蠢的错误难住了几天了,它极大地阻碍了我的进步。我认为问题与产量有关。不过我可能错了。我用手做了几十次追踪,但似乎无法找出问题所在。能不能请一些人帮忙?