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].

3
  • 8
    std::vector<std::string>> y; Commented Feb 3, 2015 at 20:49
  • 1
    The user cannot "declare" the array. Only the programmer can. Commented Feb 3, 2015 at 20:54
  • Related: Does C++ support Variable Length Arrays? and Variable length arrays in C++? The latter probably makes this question a duplicate. Commented Feb 3, 2015 at 21:10

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@jww Thanks for mentioning that. Since it was tagged as c++ I didn't want to mention C99.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.