C++ - 将 C 字符串推送到模板堆栈上

发布于 2024-09-30 12:29:30 字数 289 浏览 0 评论 0原文

我确信对于大多数人来说这是一个非常简单的问题。但我正在用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

好菇凉咱不稀罕他 2024-10-07 12:29:30

数组不可分配,因此不能用作容器值类型。

不过,您可以定义一个包含数组的结构体,并使用它:

struct Tag {
    char name[MAX];
};

stack<Tag> TagStack;

或者只使用 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:

struct Tag {
    char name[MAX];
};

stack<Tag> TagStack;

Or just use a std::string for your tags.

凉城已无爱 2024-10-07 12:29:30

如果您发布不起作用的代码,并告诉我们它如何不起作用,这将会有所帮助。 (编译时错误?运行时错误?)但我的建议是使用 std::string,至少在堆栈上:

using namespace std;
stack<string> TagStack;

您应该能够在没有显式强制转换的情况下推入堆栈:

TagStack.push(BeginTag);

注意:我不认可您的为此目的使用 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:

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; 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文