-1

This stack program runs correctly for given array size arr[5] or arr[10].But when i take size as input from the user cin>>n it says "Error: ‘cin’ does not name a type."

Here is that code:

#include <iostream>
using namespace std;

class Stack
{
private:
    int n;
    cin>>n;
    int arr[n];
    int top=-1;
public:
    rest of the code

    


So i tried to take a random input for size of array but got this error when used cin to take input. I have used namespace std but still got the error Error: ‘cin’ does not name a type.

It's my first time asking question in stack overflow so ask me if you need more clarification.

JaMiT
  • 14,422
  • 4
  • 15
  • 31
elclasico
  • 13
  • 1
  • 4
    This is not how classes work. [Here is a list of good books](https://stackoverflow.com/a/388282/6039995) to learn the basics. – Stack Danny Nov 22 '22 at 12:50
  • `int n; cin>>n; int arr[n];` is not valid standard C++. Variable Length Arrays are not allowed in standard C++. Array sizes must be a compile time constant. Use `std::vector` instead, when you need a variable length array. And forget C-style arrays exist - use `std::array` if you need a fixed size array. – Jesper Juhl Nov 22 '22 at 13:19
  • [Why aren't variable-length arrays part of the C++ standard?](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) – Jason Nov 22 '22 at 14:50

1 Answers1

1

There are two problems with this class definition

class Stack
{
private:
    int n;
    cin>>n;
    int arr[n];
    int top=-1;
    //...

The first one is that you may not use statements that are not declarations

    cin>>n;

And the second one is that variable length arrays are not a standard C++ feature.

You could define the class for example the following way

class Stack
{
private:
    int n;
    int *arr;
    int top=-1;
    //...
public:
    Stack( int n ) : n ( n < 1 ? 1 : n ), arr( new int[n] )
    {
    }
    //...  
     
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335