C++ - 将 C 字符串推送到模板堆栈上
我确信对于大多数人来说这是一个非常简单的问题。但我正在用 c++ 编写 XML 的标记识别器,并且使用堆栈来确保有匹配的开始和结束标记。好吧,我的标签是 c 字符串...
char BeginTag[MAX];
我正在尝试将其推送到我的模板堆栈上。但我不确定传递堆栈的类型。我已经尝试过...
stack<char> TagStack;
但这不起作用。我也尝试过其他一些解决方案,但似乎都不起作用。有人可以帮助我吗?
I am sure that for most this is a very easy question. But I am writing a token recoginzer for XML in c++ and I am using a stack to make sure there are matching begining and end tags. Well my tags are c strings...
char BeginTag[MAX];
I am trying to push that onto my template stack. But I am unsure what type to pass the stack. I have tried...
stack<char> TagStack;
But that doesn't work. I have tried a few other solutions alos but none seem to work. Can someone help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
数组不可分配,因此不能用作容器值类型。
不过,您可以定义一个包含数组的结构体,并使用它:
或者只使用
std::string
作为您的标签。Arrays aren't assignable, so can't be used as a container value type.
You could define a struct containing an array, though, and use that:
Or just use a
std::string
for your tags.如果您发布不起作用的代码,并告诉我们它如何不起作用,这将会有所帮助。 (编译时错误?运行时错误?)但我的建议是使用 std::string,至少在堆栈上:
您应该能够在没有显式强制转换的情况下推入堆栈:
注意:我不认可您的为此目的使用 C 字符串;我也会在标记生成器中使用 std::string 。但这是你的决定。如果继续使用 char 数组,您可能需要将 char[MAX] 更改为 char[MAX+1],因为 MAX 通常用于表示字符串中非空字符的最大数量。因此,您需要确保为终止 null 分配一个额外的字符。这可能只是一个风格问题,但也可能有助于防止错误。
It'd help if you posted the code that doesn't work, and tell us how it doesn't work. (Compile-time error? Runtime error?) But my suggestion would be to use std::string, at least on the stack:
You should be able to push onto the stack without an explict cast:
Note: I don't endorse your use of C strings for this purpose; I'd use std::string in the tokenizer also. But that's your call. If you continue using char arrays, you might want to change char[MAX] to char[MAX+1], as MAX would normally be used to denote the maximum number of non-null characters in the string. Hence, you need to ensure that there's one extra char allocated for the terminating null. This may be merely a style issue, but it may also help prevent bugs.