So i have
Class Parser and in this class is constructor

Parser(string s){ // constructor
tokens = s.c_str(); // convert to a C string
opStack.push(END); // initialize opStack


}

tokens was defined as const char *tokens in private ;

That is in the parser.h file
However when i try to cout tokens in an implemented method in parser.cpp..it prints out garbage...and weird looking symbols. If i cout tokens in the constructor..it prints out the string..which is what its supposed to do..So how is it that when i move outside the constructor, it changes?

My main goes like this..

cout << "Enter expression: ";
cin.get(line, 100); 
cin.ignore(100, '\n');
str = string(line); //convert line to a string
if (str == "quit") break;
Parser par(str); // new parser
par.toPostfix();

As you can see the constuctor for par is called...I can cout tokens correctly if i put it in the constructor..However once i put it in toPostfix() it prints out weird looking symbols.

Edited 6 Years Ago by karolik: n/a

if it a pointer you need to dereference the variable otherwise you are getting the memory location. use *tokens to dereference pointer.

Class Parser and in this class is constructor

Parser(string s){ // constructor
}

Parser constructor takes a temporary string, i.e. once the Parser object is constructed, the string s object is destructed, hence tokens ends up pointing to deleted memory (i.e. garbage).
You might pass the string in by reference, in which case tokens would be usable as long as the external string exists. Or have a new string member variable that takes a copy of the passed-in string (that would be safe).

This article has been dead for over six months. Start a new discussion instead.