2

something like

ifstream myfile ("example.txt");
        if (myfile.is_open())
        {
            while ( getline (myfile,line) )
            {
                nr++; //how many lines in a text file
            }
        }

string y[nr] = {};

only works when I specify actual number like y[10].

jww
  • 97,681
  • 90
  • 411
  • 885
  • 8
    std::vector> y; – Creris Feb 03 '15 at 20:49
  • 1
    The user cannot "declare" the array. Only the programmer can. –  Feb 03 '15 at 20:54
  • Related: [Does C++ support Variable Length Arrays?](http://stackoverflow.com/q/8593643/608639) and [Variable length arrays in C++?](http://stackoverflow.com/q/1887097/608639) The latter probably makes this question a duplicate. – jww Feb 03 '15 at 21:10

1 Answers1

3

You cannot declare arrays with an unknown size unless you are using a non portable compiler extension. The standard way to accomplish this is to use a vector.

int x;
cout << "Size of your array: ";
cin >> x;
vector<string> y(x);
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • Variable-length automatic arrays are allowed in ISO C99. As an extension, GCC accepts variable-length arrays as a member of a structure or a union. See GCC's [6.19 Arrays of Variable Length](https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html). – jww Feb 03 '15 at 21:08
  • 1
    @jww Thanks for mentioning that. Since it was tagged as c++ I didn't want to mention C99. – NathanOliver Feb 03 '15 at 21:22