1

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?

Johnrad
  • 2,637
  • 18
  • 58
  • 98

2 Answers2

3

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.

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
1

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.

Dan Breslau
  • 11,472
  • 2
  • 35
  • 44
  • The code that doesn't work is `TagStack.push(BeginTag)`, given the declarations in the OP's question. Incompatible types. – Cascabel Nov 05 '10 at 20:52
  • I figured as such, but it's better for posters to be as clear as they can be about the problems they're seeing. – Dan Breslau Nov 05 '10 at 20:53
  • I figured out how. I need to the type of the teplate to be a char pointer. Which point's to the first character of the string – Johnrad Nov 05 '10 at 20:55
  • That's unlikely to work! This will probably result in your stack containing pointers that point to unallocated, or re-written, memory. In the "best" case, perhaps, all the pointers in your stack will actually point to the same memory address, giving you multiple copies of the same string. – Dan Breslau Nov 05 '10 at 21:05
  • If you're not familiar yet with the proper use of new and delete, as well as templated pointers such as auto_ptr or shared_ptr, then you should probably avoid using pointers at all. (If you think your answer uses pointers, you should try to find another answer.) – Dan Breslau Nov 05 '10 at 21:05