使用模板时,Visual Studio C ++向控制台输出奇怪的字符

时间:2015-02-06 04:01:13

标签: c++ templates character

当我尝试使用VS 2013将某些字符输出到控制台时,我遇到了问题。

这是角色看起来像(2)enter image description here之后的图像。我已经使用“+ - / *”符号进行了测试,并且每个符号都会出现。

基本上,我的程序使用堆栈类作为模板来保存字符,然后稍后拉出这些字符。这是我的堆栈类。

#include <assert.h>

template <class Item>
class stack
{
public:
    //TYPEDEFS AND MEMBER CONSTANT
    typedef int size_type; 
    typedef Item value_type;
    static const size_type CAPACITY = 30;
    //Constructor
    stack() { used = 0; } //Postcondition: The stack has been initialized as an empty stack.
    //Modification member functions
    void push(const Item& entry); //Precondition: size() < CAPACITY. Postcondition: A new copy of entry has been pushed onto the stack.
    void pop(); //Precondition: size() > 0. Postcondition:The top item of the stack has been removed.
    //Constant member functions
    bool empty() const { return (used == 0); } //Postcondition: The return value is true if the stack is empty, and false otherwise.
    size_type size() const { return used; } //Postcondition: The return value is the total number of items in the stack.
    Item top() const; //Precondition: size() > 0. Postcondition: The return value is the top item of the stack, but the stack is unchanged. This differs slightly from the STL stack (where the top function returns a reference to the item on top of the stack).
private:
    Item data[CAPACITY]; //Partially filled array.
    size_type used;
};

template <class Item>
void stack<Item>::push(const Item& entry) {
    assert(size() < CAPACITY);
    data[used] = entry;
    used++;
}

template <class Item>
void stack<Item>::pop() {
    assert(size() > 0);
    used--;
}

template <class Item>
Item stack<Item>::top() const {
    assert(size() > 0);
    return data[used];
}

然后我的驱动程序使用myStack.push(pString[pos]);保存一个字符,稍后用cout << myStack.top();输出

有谁知道如何让它显示正确的字符?感谢。

1 个答案:

答案 0 :(得分:2)

此:

template <class Item>
Item stack<Item>::top() const {
    assert(size() > 0);
    return data[used];
}
used == size()开始,

会返回一个结尾。你想要:

return data[used - 1];