词法分析器项目 - 矢量未正确输出
Lexical Analyzer Project - Vector not outputting correctly
我有以下代码,它是一个更大项目的一部分。这段代码应该做的是逐行逐行查找"令牌"。我在此代码中查找的令牌是 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;
}
这将完成变量定义中的所有工作,并调用范围构造函数。所以,典型的单行本。
希望有人能从这段代码中学习。 .
相关文章:
- Directx11 项目将不显示图形输出
- 通过查找一对项目的代码获取错误的输出,在给定的总和相等的给定列表中列表
- 如何最好地为 Visual Studio 2017 构建的 CMake C++ 项目设置输出目录
- 复制C DLL以构建任何C#项目的输出,以扩展为参考
- 词法分析器项目 - 矢量未正确输出
- 如何获取外部项目定义的目标的输出路径?
- 如何将.EXE从C 项目复制到C#项目的输出目录
- 如何将项目添加到输出文件中
- 调整项目在Visual Studio的输出窗口中构建报告
- 欧拉项目 #14 代码输出未到来
- 将两个VS2010 C++项目构建到同一输出文件夹中
- 有没有办法设置 Eclipse 以使用另一个项目的输出作为库?
- 此项目不会将整数读取为二进制并将其作为二进制输出到新文件
- 无法将外部git-CMake项目的输出(静态库)链接到CMake项目
- 将dll与c++项目中的其他输出文件分离
- 具有多个DLL输出的项目
- Netbeans C/C++项目中的代码相同,但输出不同
- 配置 VS2010 以将C++项目构建到合理干净的输出目录
- Gradle C(本机)任务输出文件(用于其他任务/项目)
- 从 excel 到 cpp 项目的输入和输出