-3

I receive these errors 1. cannot allocate an array of constant size 0 2. expected constant expression 3. 'numbers' : unknown size

#include <iostream>
#include <string>
using namespace std;

int main()
{
string str;
int input_num;
int sum;

cout << "Enter the number:" << endl;
getline(cin, str);
const int length = str.length();
cout << "Length:" << length<<endl;
//input_num = stoi(str);
int numbers[length];

return 0;

}
  • You cannot declare a stack allocated array who's size is not known at compile time (without a compiler extension) – Cory Kramer Apr 09 '15 at 20:21
  • 1
    Unfortunately, that duplicate doesn't mention that you should just use `std::vector` because it's explicitly disallowed in the title. – chris Apr 09 '15 at 20:21
  • Just as a heads up for anybody else arriving here searching for the same thing I was 4 years later, the answer with the vector is EXACTLY what I needed and granted that this question had it's issues in the way it was asked, there's no reason it should keep getting downvoted. I appreciate the question and the answer. It's what I needed and props to SO for fulfilling it's purpose. – pianoman102 Jun 25 '19 at 20:46

2 Answers2

1

Replace the use of an array by a std::vector, and initialize the elements to 0.

std::vector<int> numbers(length, 0);
R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

The size of an array has to be a constant expression greater than 0.

You should use standard class std::vector<int> instead.

For example

#include <vector>

//...

std::vector<int> numbers( length );

If the user has to enter a number of type for example int (that is the number might be in the range of acceptable values of object of type int) then you could define the array beforehand the following way

#include <limits>

//...

int numbers[std::limits<int>::digits10 + 1];
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335