我正在用我的编程语言编写一个翻译器,这是一种过于简单的C++,我有关于解析一行的问题。在C++中,我们将一些对象定义为:
class Item{
string Item;
string Item2;
};我想使用关键字add在我的语言中创建相同的对象:
add "Item Item", "Item2 Item2";如您所见,项目变量“string *”可以是带有空格的行。
但是我需要解析它并生成一个数组的命令堆栈。在这个例子中,我想要解析这行代码,生成3的数组,如下所示:[add, Item Item, Item2 Item2]。因此,我需要保存"Item Item“之间的空格,并在解析时将其计为一个字符串行,但仍然使用空格作为add和第一个"Item*”之间的分隔符。我该怎么做?
发布于 2016-03-29 22:55:12
如果使用Boost,则可以使用split函数。我没有捕捉到所有潜在的错误,但它以相当容易理解的代码给出了正确的答案。我所做的是在引号上拆分代码。在引号之前有一个动作,在第一个引号之间是第一项,然后是逗号,在第二组引号之间是第二项:
#include <iostream>
#include <vector>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
class Item_container
{
public:
Item_container(const std::string& s)
{
std::cout << "Input string: " << s << std::endl;
std::vector<std::string> string_vector;
boost::split(string_vector, s, boost::is_any_of("\""));
// Below, error checking should be implemented
stack.push_back(string_vector[0]);
stack.push_back(string_vector[1]);
stack.push_back(string_vector[3]);
}
std::vector<std::string> get_stack() const { return stack; }
private:
std::vector<std::string> stack;
};
int main()
{
Item_container item_container("add \"Item Item\", \"Item2 Item2\";");
for (auto &s : item_container.get_stack())
std::cout << s << std::endl;
return 0;
}发布于 2016-03-29 22:56:01
这是一个小的标记器。这只是一个示例;它没有错误检查,因此它很可能会在意外输入时崩溃。包含文件包括iostream、string、vector和ctype.h。
enum st
{
inSpace,
inToken,
inString
};
static st newstate(const char* p)
{
if (isalpha(*p))
{
return inToken;
}
if ('"' == *p)
{
return inString;
}
return inSpace;
}
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
char line[128];
std::cin.getline(line, sizeof(line));
st state = inSpace;
char* p = line;
char* ptok = nullptr; // Will point to the beginning of a token
std::vector<std::string*> sym;
while(*p)
{
switch(state)
{
case inSpace:
while(isspace(*p) || (',' == *p))
{
++p;
}
state = newstate(p);
break;
case inString:
ptok = p; // Token includes opening quote
while('"' != *++p);
sym.push_back(new std::string(ptok, p + 1));
state = newstate(++p);
break;
case inToken:
ptok = p;
while(isalpha(*++p));
sym.push_back(new std::string(ptok, p));
state = newstate(p);
break;
default:
std:: cout << "Error\n";
}
}
for(int i = 0; sym.size() > i; ++i)
{
std::cout << "Symbol #" << i + 1 << " = " << *(sym[i]) << std::endl;
}
return 0;
}https://stackoverflow.com/questions/36285358
复制相似问题