简体   繁体   English

堆栈c ++的打印功能

[英]print function for stack c++

I am trying to print the contents of my stack. 我正在尝试打印堆栈中的内容。 here is my code: Stack.h 这是我的代码:Stack.h

#pragma once
#include <iostream>

using std::cout;                            // specific commands from namespace std
using std::cin;
using std::endl;

typedef unsigned long Item;

class Stack
{
private:
    enum { MAX = 10 };  // MAX elements in this stack
    Item items[MAX];    // holds stack items
    int top;            // index for the top stack item
    int first, last;

public:
    Stack();
    Stack(int, int);
    ~Stack();
    void printCurr() const;
    void printCurrReverse() const;
    bool isempty() const;
    bool isfull() const;
    // return false if stack already full
    bool push(const Item& item);    // add item to stack
                                    // return false if stack already empty
    bool pop(Item& item);

};

stack.cpp stack.cpp

#pragma once
#include "Stack.h"
#include <iostream>
using std::cout;
using std::cin;
using std::endl;


Stack::Stack()
{
    for (int i = 0; i < MAX; i++) //for loop that sets the initial array values to null
    {
        items[i] = 0;
    }   
    top = 0;
}


Stack::Stack(int first , int last)
{

    if (top <= 4)
    {
        for (int i = 0; i <= 4; i++)
        {
            this -> items[i] = first;
        }
    }

    if (top >= 5 && top <= MAX)
    {
        for (int i = 0; i <= MAX; i++)
        {
            this -> items[i] = last;
        }
    }

}

Stack::~Stack()
{
}


void Stack::printCurr() const
{
    int index = 0;
    for (int i = index; i < MAX; i++)
    {
        cout << index + i;
    }
}

void Stack::printCurrReverse() const
{
    int index = top - 1;
    for (int i = index; i >= 0; i++)
    {
        cout << index + i;
    }
}



bool Stack::isempty() const
{
    return top == 0;
}

bool Stack::isfull() const
{
    return top == MAX;
}

bool Stack::push(const Item& item)
{
    if (top < MAX)
    {
        items[top++] = item;
        return true;
    }
    else
        return false;
}

bool Stack::pop(Item& item)
{
    if (top > 0)
    {
        item = items[--top];
        return true;
    }
    else
        return false;
}

main.cpp main.cpp

#include <iostream>
#include <sstream>
#include "Stack.h"


using namespace std;

int main()
{

    Stack st1;

    char ch;
    unsigned long sc;
    cout << "Please Enter 'A' to Add A Score You Wish To Record, \n"
        << "Press R To Record A Score, V To View Recorded Scores & Q to Quit" << endl;
    while (cin >> ch && toupper(ch) != 'Q')
    {
        while (cin.get() != '\n')
            continue;
        if (!isalpha(ch))
        {
            cout << '\a';
            continue;
        }
        switch (ch)
        {
        case 'a':
        case 'A': cout << "Enter A Score To Add: ";
            cin >> sc;
            if (st1.isfull())
                cout << "stack already full\n";
            else
                st1.push(sc);
            break;
        case 'R':
        case 'r': if (st1.isempty())
            cout << "stack already empty\n";
                  else {
                      st1.pop(sc);
                      cout << "Score #" << sc << " popped\n";
                  }
                  break;
        case 'V':
        case 'v':

            cout << "Your Recorded Scores are : " << st1.printCurr() << endl;
            cout << "Your Recorded Scores In Reverse Order Are : " << st1.printCurrReverse() << endl;

            cout << "Please enter A to add a purchase order,\n"
                << "P to process a PO, or Q to quit.\n";
        }

        system("pause");
        return 0;
    }
}

my problem is the print functions. 我的问题是打印功能。 I am getting the following error 我收到以下错误

Error C2679 binary '<<': no operator found which takes a right-hand operand of type 'void' (or there is no acceptable conversion)
main.cpp 48

from what I understand this is happening because I am not overloading the << operator correctly. 据我了解,这是因为我没有正确地重载<<操作符。

I need the print function to be with out parameters and without a return value. 我需要print函数没有参数并且没有返回值。 What am I doing wrong? 我究竟做错了什么?

Your print functions printCurr and printCurrReverse return void, and therefore cannot be used as parameter of std::cout (in your main ). 您的打印函数printCurrprintCurrReverse返回void,因此不能用作std::cout参数(在main )。 Your functions already print it with cout. 您的函数已经使用cout打印了。

You could let your function return string instead. 您可以让函数返回字符串。 Or remove them from the cout line. 或将其从cout移除。

The simplest way, put them out of the cout line: 最简单的方法是将它们放在提示行之外:

cout << "Your Recorded Scores are : ";
st1.printCurr();
cout << "Your Recorded Scores In Reverse Order Are : "; 
st1.printCurrReverse();

Otherwise let your print functions return a string which you can create with stringstream for example: 否则,让您的打印函数返回可以使用stringstream创建的string ,例如:

std::string printCurrReverse() {
  stringstream strs;
  strs << " text "<< 33; //example
  return strs.str();
}

First of all this constructor 首先,这个构造函数

Stack::Stack(int first , int last)
{

    if (top <= 4)
    {
        for (int i = 0; i <= 4; i++)
        {
            this -> items[i] = first;
        }
    }

    if (top >= 5 && top <= MAX)
    {
        for (int i = 0; i <= MAX; i++)
        {
            this -> items[i] = last;
        }
    }

}

does not make sense and has undefined behaviour because data member top is not initialized. 没有意义,并且具有未定义的行为,因为未初始化数据成员top。 And it is not clear what you are trying to do. 目前尚不清楚您要做什么。

Function printCurr also does not make sense 函数printCurr也没有意义

void Stack::printCurr() const
{
    int index = 0;
    for (int i = index; i < MAX; i++)
    {
        cout << index + i;
    }
}

It simply outputs natural numbers in the range [0, MAX - 1] 它仅输出[0, MAX - 1]范围内的自然数

If you mean to output the values stored in the stack then the function can look the following way 如果要输出存储在堆栈中的值,则该函数可以采用以下方式

void Stack::printCurr() const
{
    for ( int i = top; i != 0; )
    {
        cout << items[--i];
    }
}

Correspondingly function printCurrReverse can look like 相应的函数printCurrReverse可以看起来像

void Stack::printCurrReverse() const
{
    for ( int i = 0; i != top ; i++)
    {
        cout << items[i];
    }
}

Else as the functions have return type void you may not use them like 否则,由于函数具有返回类型void,因此您可能无法像

cout << "Your Recorded Scores In Reverse Order Are : " << st1.printCurrReverse() << endl;

If you want to use them such a way then they should be defined like 如果要以这种方式使用它们,则应将它们定义为

std::ostream & Stack::printCurr( std::ostream &os = std::cout ) const
{
    for ( int i = top; i != 0; )
    {
        os << items[--i];
    }

    return os;
}

and

std::ostream & Stack::printCurrReverse( std::ostream &os = std::cout ) const
{
    for ( int i = 0; i != top ; i++)
    {
        os << items[i];
    }

    return os;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM