[英]C++ - Pushing a C-String onto a Template Stack
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.
但我正在用c ++编写XML的令牌recoginzer,我正在使用堆栈来确保匹配的开始和结束标记。 Well my tags are c strings...
那么我的标签是c字符串......
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?
有人能帮我吗?
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: 但是,您可以定义包含数组的结构,并使用它:
struct Tag {
char name[MAX];
};
stack<Tag> TagStack;
Or just use a std::string
for your tags. 或者只为标签使用
std::string
。
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:
(编译时错误?运行时错误?)但我的建议是使用std :: string,至少在堆栈上:
using namespace std;
stack<string> TagStack;
You should be able to push onto the stack without an explict cast: 你应该能够在没有明确演员的情况下进入堆栈:
TagStack.push(BeginTag);
Note: I don't endorse your use of C strings for this purpose; 注意:我不认可您为此目的使用C字符串; I'd use std::string in the tokenizer also.
我也在tokenizer中使用std :: string。 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.
如果继续使用char数组,则可能需要将char [MAX]更改为char [MAX + 1],因为MAX通常用于表示字符串中的最大非空字符数。 Hence, you need to ensure that there's one extra char allocated for the terminating null.
因此,您需要确保为终止null分配了一个额外的char。 This may be merely a style issue, but it may also help prevent bugs.
这可能只是一个样式问题,但它也可能有助于防止错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.