-3

I have a file input.txt like:

n
a1 a3 a3 an

where n is quantity of elements(array size), and a1 a2 a3 an are the elements.

How can I create an array of a1, a2, a3, an objects? I tried to do this using example from this question, but as I understand I can't create array in the loop as it will create it on every iteration.

Community
  • 1
  • 1
pythad
  • 4,241
  • 2
  • 19
  • 41
  • 1
    Start with the knowledge that C++ doesn't have [variable-length arrays](http://en.wikipedia.org/wiki/Variable-length_array) or other dynamic arrays. It *does* have [`std::vector`](http://en.cppreference.com/w/cpp/container/vector) though. Then think about where you need to declare this vector for it to be available both inside the loop *and* after the loop is done, and without being "recreated" inside the loop. – Some programmer dude Nov 09 '15 at 14:48
  • (1) read the first line and convert the string to an integer. (2) declare or allocate an array (or other suitable data structure) of length `n` (given in (1)). (3) read the next line of the file and parse out `n` elements (you haven't mentioned their types so I leave *parse* definition to you). If this isn't helpful, then I think you need to do some C++ tutorials to get grounded in the basics of the language. You could do an internet search on "C++ read data from file" for example. – lurker Nov 09 '15 at 14:51
  • 1
    As `n` is known in advance, one dynamic allocation also does the trick. But I'm sure you don't have heavy performance requirements, so just stick to `vector` and perhaps use `reserve`. – Karoly Horvath Nov 09 '15 at 14:52

3 Answers3

3

Simply create a vector, something like this:

ifstream fin("inout.txt", ios::in | ios::binary);
int n;
fin >> n;
vector<int> v;
int m;
while (n--) {
    fin >> m;
    v.push_back(m);
}

Then you can always get an array from

int *array = v.data();
Paul Evans
  • 27,315
  • 3
  • 37
  • 54
1

Assuming that a1, a2, a3, an are integers like

4
1 2 3 4

An example implementation:

#include <cstdio>

int main(void) {
    int n;
    int *a;
    FILE* fp;

    // read the text and create an array
    fp = fopen("input.txt", "r");
    if (fp == NULL) return 1;
    if (fscanf(fp, "%d", &n) != 1) return 1;
    a = new int[n];
    for (int i = 0; i < n; i++) {
        if (fscanf(fp, "%d", &a[i]) != 1) return 1;
    }
    fclose(fp);

    // print the array for checking
    for (int i = 0; i < n; i++) printf("%d\n", a[i]);

    delete[] a;
    return 0;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
1

but as I understand I can't create array in the loop as it will create it on every iteration.

You're correct.

If you don't want to create a new array on every iteration, then don't create the array in the loop. Create it outside the loop.

eerorika
  • 232,697
  • 12
  • 197
  • 326