Bianca0745
Bianca0745

Reputation: 23

Stack of strings with templates?

I'm trying to make a push function for my class Stack but I keep getting errors. This is my code: (before you ask, I know using namespace std is a bad idea; we are required to use it now...).

header:

#pragma once
#include <string.h>
using namespace std;
template <class T>
class Stack {
    T List[100];
    int size;
public:
    Stack() : size(0){}
    void push(const T &x)
    {
        strcpy(List[size++], x);
    }
    const T& pop() {
        if (size != 0) return List[size - 1];
    }
    T print()
    {
        for (int i = 0; i < size; i++)
            cout << List[i] << " ";
    }
    T reverse();
};

main

#include <iostream>
#include"Stack.h"
#include <string.h>
using namespace std;
int main()
{
    Stack<string> S;
    S.push("ana");
    S.push("are");
    S.push("mere");
    S.print();
}

my error is in strcpy: cannot convert argument 1 from T to char * .

Upvotes: 1

Views: 187

Answers (1)

cigien
cigien

Reputation: 60268

You don't need to use strcpy here, you can just use = to assign the input:

void push(const T &x)
{
   List[size++] = x;
}

There are some other issues in your code. In pop, you are not decrementing size, and you are not returning if the List is empty. One option is just to throw if there is nothing to return:

const T& pop() 
{
    if (size != 0) 
        return List[size--];
    throw;
}

Also, you are not returning from print. However, there doesn't appear to be any meaningful value to return, so you could make it a void function:

void print()
{
    for (int i = 0; i < size; i++)
         cout << List[i] << " "; 
}

Here's a demo.

Upvotes: 1

Related Questions