stack <char> stck;
string str;
stck.push('0');
str.append("test:");
//test:
cout << str << endl;
str.append(&stck.top());
//test:0═══════════════¤¤¤¤▌▌▌▌,╘╥XЕ┤
cout << str << endl;
Why is this happening?
stack <char> stck;
string str;
stck.push('0');
str.append("test:");
//test:
cout << str << endl;
str.append(&stck.top());
//test:0═══════════════¤¤¤¤▌▌▌▌,╘╥XЕ┤
cout << str << endl;
Why is this happening?
&stck.top()
is an address of the char
that is on the top of the stack. The type of this expression is char*
.
The overload of append
method, that takes char*
(actually the signature is string& append ( const char* s );
) expects the pointer to point to the beginning of a null-terminated string and interprets the argument in this way. It appends the character pointed to by the argument and then all the consecutive characters in the memory, up to the first null character. It reads and copies an area of the memory, that doesn't belong to the stack.
Maciej Hehl is correct about why you're getting unwanted behavior.
To get the behavior that you want, you need to append the character itself, not a pointer to it. You are correct in saying (in your comment to Kalim's answer) that there is no override of std::string::append
that takes just a char
. However, there is an override std::string::append(std::size_t, char)
, which appends the character (second argument) a certain number of times (first argument).
So the correct way to write what you want would be:
str.append(1, stck.top()); // Append one copy of the character at the top of the stack
Or, alternatively, just use the overload for the +=
operator, which accepts a char
:
str += stck.top();